16 humanize "github.com/dustin/go-humanize"
17 "github.com/mitchellh/go-homedir"
20 // A Command contains a action (a function to call) as well as information about how to autocomplete the command
23 completions []Completion
26 // A StrCommand is similar to a command but keeps the name of the action
27 type StrCommand struct {
29 completions []Completion
32 var commands map[string]Command
34 var commandActions map[string]func([]string)
37 commandActions = map[string]func([]string){
46 "ReplaceAll": ReplaceAll,
52 "ToggleLog": ToggleLog,
58 "TabSwitch": TabSwitch,
63 // InitCommands initializes the default commands
65 commands = make(map[string]Command)
67 defaults := DefaultCommands()
68 parseCommands(defaults)
71 func parseCommands(userCommands map[string]StrCommand) {
72 for k, v := range userCommands {
73 MakeCommand(k, v.action, v.completions...)
77 // MakeCommand is a function to easily create new commands
78 // This can be called by plugins in Lua so that plugins can define their own commands
79 func MakeCommand(name, function string, completions ...Completion) {
80 action := commandActions[function]
81 if _, ok := commandActions[function]; !ok {
82 // If the user seems to be binding a function that doesn't exist
83 // We hope that it's a lua function that exists and bind it to that
84 action = LuaFunctionCommand(function)
87 commands[name] = Command{action, completions}
90 // DefaultCommands returns a map containing micro's default commands
91 func DefaultCommands() map[string]StrCommand {
92 return map[string]StrCommand{
93 "set": {"Set", []Completion{OptionCompletion, OptionValueCompletion}},
94 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
95 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
96 "bind": {"Bind", []Completion{NoCompletion}},
97 "run": {"Run", []Completion{NoCompletion}},
98 "quit": {"Quit", []Completion{NoCompletion}},
99 "save": {"Save", []Completion{NoCompletion}},
100 "replace": {"Replace", []Completion{NoCompletion}},
101 "replaceall": {"ReplaceAll", []Completion{NoCompletion}},
102 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
103 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
104 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
105 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
106 "eval": {"Eval", []Completion{NoCompletion}},
107 "log": {"ToggleLog", []Completion{NoCompletion}},
108 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
109 "reload": {"Reload", []Completion{NoCompletion}},
110 "cd": {"Cd", []Completion{FileCompletion}},
111 "pwd": {"Pwd", []Completion{NoCompletion}},
112 "open": {"Open", []Completion{FileCompletion}},
113 "tabswitch": {"TabSwitch", []Completion{NoCompletion}},
114 "memusage": {"MemUsage", []Completion{NoCompletion}},
118 // PluginCmd installs, removes, updates, lists, or searches for given plugins
119 func PluginCmd(args []string) {
123 installedVersions := GetInstalledVersions(false)
124 for _, plugin := range args[1:] {
125 pp := GetAllPluginPackages().Get(plugin)
127 messenger.Error("Unknown plugin \"" + plugin + "\"")
128 } else if err := pp.IsInstallable(); err != nil {
129 messenger.Error("Error installing ", plugin, ": ", err)
131 for _, installed := range installedVersions {
132 if pp.Name == installed.pack.Name {
133 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
134 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
136 messenger.Error(pp.Name, " is already installed")
145 for _, plugin := range args[1:] {
146 // check if the plugin exists.
147 if _, ok := loadedPlugins[plugin]; ok {
148 UninstallPlugin(plugin)
149 removed += plugin + " "
153 if !IsSpaces(removed) {
154 messenger.Message("Removed ", removed)
156 messenger.Error("The requested plugins do not exist")
159 UpdatePlugins(args[1:])
161 plugins := GetInstalledVersions(false)
162 messenger.AddLog("----------------")
163 messenger.AddLog("The following plugins are currently installed:\n")
164 for _, p := range plugins {
165 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
167 messenger.AddLog("----------------")
168 if len(plugins) > 0 {
169 if CurView().Type != vtLog {
170 ToggleLog([]string{})
174 plugins := SearchPlugin(args[1:])
175 messenger.Message(len(plugins), " plugins found")
176 for _, p := range plugins {
177 messenger.AddLog("----------------")
178 messenger.AddLog(p.String())
180 messenger.AddLog("----------------")
181 if len(plugins) > 0 {
182 if CurView().Type != vtLog {
183 ToggleLog([]string{})
187 packages := GetAllPluginPackages()
188 messenger.AddLog("Available Plugins:")
189 for _, pkg := range packages {
190 messenger.AddLog(pkg.Name)
192 if CurView().Type != vtLog {
193 ToggleLog([]string{})
197 messenger.Error("Not enough arguments")
201 // TabSwitch switches to a given tab either by name or by number
202 func TabSwitch(args []string) {
204 num, err := strconv.Atoi(args[0])
206 // Check for tab with this name
209 for _, t := range tabs {
210 v := t.views[t.CurView]
211 if v.Buf.GetName() == args[0] {
217 messenger.Error("Could not find tab: ", err)
221 if num >= 0 && num < len(tabs) {
224 messenger.Error("Invalid tab index")
230 // Cd changes the current working directory
231 func Cd(args []string) {
233 home, _ := homedir.Dir()
234 path := strings.Replace(args[0], "~", home, 1)
236 for _, tab := range tabs {
237 for _, view := range tab.views {
239 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
240 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
241 view.Buf.Path = view.Buf.AbsPath
248 // MemUsage prints micro's memory usage
249 // Alloc shows how many bytes are currently in use
250 // Sys shows how many bytes have been requested from the operating system
251 // NumGC shows how many times the GC has been run
252 // Note that Go commonly reserves more memory from the OS than is currently in-use/required
253 // Additionally, even if Go returns memory to the OS, the OS does not always claim it because
254 // there may be plenty of memory to spare
255 func MemUsage(args []string) {
256 var mem runtime.MemStats
257 runtime.ReadMemStats(&mem)
259 messenger.Message(fmt.Sprintf("Alloc: %v, Sys: %v, NumGC: %v", humanize.Bytes(mem.Alloc), humanize.Bytes(mem.Sys), mem.NumGC))
262 // Pwd prints the current working directory
263 func Pwd(args []string) {
264 wd, err := os.Getwd()
266 messenger.Message(err.Error())
268 messenger.Message(wd)
272 // Open opens a new buffer with a given filename
273 func Open(args []string) {
276 // the filename might or might not be quoted, so unquote first then join the strings.
277 filename = strings.Join(SplitCommandArgs(filename), " ")
279 CurView().Open(filename)
281 messenger.Error("No filename")
285 // ToggleLog toggles the log view
286 func ToggleLog(args []string) {
287 buffer := messenger.getBuffer()
288 if CurView().Type != vtLog {
289 CurView().HSplit(buffer)
290 CurView().Type = vtLog
292 buffer.Cursor.Loc = buffer.Start()
294 buffer.Cursor.Loc = buffer.End()
301 // Reload reloads all files (syntax files, colorschemes...)
302 func Reload(args []string) {
306 // Help tries to open the given help page in a horizontal split
307 func Help(args []string) {
309 // Open the default help if the user just typed "> help"
310 CurView().openHelp("help")
313 if FindRuntimeFile(RTHelp, helpPage) != nil {
314 CurView().openHelp(helpPage)
316 messenger.Error("Sorry, no help for ", helpPage)
321 // VSplit opens a vertical split with file given in the first argument
322 // If no file is given, it opens an empty buffer in a new split
323 func VSplit(args []string) {
325 CurView().VSplit(NewBufferFromString("", ""))
328 home, _ := homedir.Dir()
329 filename = strings.Replace(filename, "~", home, 1)
330 file, err := os.Open(filename)
331 fileInfo, _ := os.Stat(filename)
333 if err == nil && fileInfo.IsDir() {
334 messenger.Error(filename, " is a directory")
342 // File does not exist -- create an empty buffer with that name
343 buf = NewBufferFromString("", filename)
345 buf = NewBuffer(file, FSize(file), filename)
347 CurView().VSplit(buf)
351 // HSplit opens a horizontal split with file given in the first argument
352 // If no file is given, it opens an empty buffer in a new split
353 func HSplit(args []string) {
355 CurView().HSplit(NewBufferFromString("", ""))
358 home, _ := homedir.Dir()
359 filename = strings.Replace(filename, "~", home, 1)
360 file, err := os.Open(filename)
361 fileInfo, _ := os.Stat(filename)
363 if err == nil && fileInfo.IsDir() {
364 messenger.Error(filename, " is a directory")
372 // File does not exist -- create an empty buffer with that name
373 buf = NewBufferFromString("", filename)
375 buf = NewBuffer(file, FSize(file), filename)
377 CurView().HSplit(buf)
381 // Eval evaluates a lua expression
382 func Eval(args []string) {
384 err := L.DoString(args[0])
389 messenger.Error("Not enough arguments")
393 // NewTab opens the given file in a new tab
394 func NewTab(args []string) {
396 CurView().AddTab(true)
399 home, _ := homedir.Dir()
400 filename = strings.Replace(filename, "~", home, 1)
401 file, err := os.Open(filename)
402 fileInfo, _ := os.Stat(filename)
404 if err == nil && fileInfo.IsDir() {
405 messenger.Error(filename, " is a directory")
413 buf = NewBufferFromString("", filename)
415 buf = NewBuffer(file, FSize(file), filename)
418 tab := NewTabFromView(NewView(buf))
419 tab.SetNum(len(tabs))
420 tabs = append(tabs, tab)
421 curTab = len(tabs) - 1
423 for _, t := range tabs {
424 for _, v := range t.views {
432 // Set sets an option
433 func Set(args []string) {
435 messenger.Error("Not enough arguments")
442 SetOptionAndSettings(option, value)
445 // SetLocal sets an option local to the buffer
446 func SetLocal(args []string) {
448 messenger.Error("Not enough arguments")
455 err := SetLocalOption(option, value, CurView())
457 messenger.Error(err.Error())
461 // Show shows the value of the given option
462 func Show(args []string) {
464 messenger.Error("Please provide an option to show")
468 option := GetOption(args[0])
471 messenger.Error(args[0], " is not a valid option")
475 messenger.Message(option)
478 // Bind creates a new keybinding
479 func Bind(args []string) {
481 messenger.Error("Not enough arguments")
484 BindKey(args[0], args[1])
487 // Run runs a shell command in the background
488 func Run(args []string) {
489 // Run a shell command in the background (openTerm is false)
490 HandleShellCommand(JoinCommandArgs(args...), false, true)
493 // Quit closes the main view
494 func Quit(args []string) {
495 // Close the main view
499 // Save saves the buffer in the main view
500 func Save(args []string) {
502 // Save the main view
505 CurView().Buf.SaveAs(args[0])
509 // Replace runs search and replace
510 func Replace(args []string) {
511 if len(args) < 2 || len(args) > 3 {
512 // We need to find both a search and replace expression
513 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
519 // user added -a flag
523 messenger.Error("Invalid replace flag: " + args[2])
528 search := string(args[0])
529 replace := string(args[1])
531 regex, err := regexp.Compile("(?m)" + search)
533 // There was an error with the user's regex
534 messenger.Error(err.Error())
541 replaceAll := func() {
543 deltaXOffset := Count(replace) - Count(search)
544 for i := 0; i < view.Buf.LinesNum(); i++ {
545 matches := regex.FindAllIndex(view.Buf.lines[i].data, -1)
546 str := string(view.Buf.lines[i].data)
550 for _, m := range matches {
551 from := Loc{runePos(m[0], str) + xOffset, i}
552 to := Loc{runePos(m[1], str) + xOffset, i}
554 xOffset += deltaXOffset
556 deltas = append(deltas, Delta{replace, from, to})
561 view.Buf.MultipleReplace(deltas)
568 // The 'check' flag was used
569 Search(search, view, true)
570 if !view.Cursor.HasSelection() {
575 choice, canceled := messenger.LetterPrompt("Perform replacement? (y,n,a)", 'y', 'n', 'a')
577 if view.Cursor.HasSelection() {
578 view.Cursor.Loc = view.Cursor.CurSelection[0]
579 view.Cursor.ResetSelection()
583 } else if choice == 'a' {
584 if view.Cursor.HasSelection() {
585 view.Cursor.Loc = view.Cursor.CurSelection[0]
586 view.Cursor.ResetSelection()
591 } else if choice == 'y' {
592 view.Cursor.DeleteSelection()
593 view.Buf.Insert(view.Cursor.Loc, replace)
594 view.Cursor.ResetSelection()
598 if view.Cursor.HasSelection() {
599 searchStart = view.Cursor.CurSelection[1]
601 searchStart = view.Cursor.Loc
605 view.Cursor.Relocate()
608 messenger.Message("Replaced ", found, " occurrences of ", search)
609 } else if found == 1 {
610 messenger.Message("Replaced ", found, " occurrence of ", search)
612 messenger.Message("Nothing matched ", search)
616 // ReplaceAll replaces search term all at once
617 func ReplaceAll(args []string) {
618 // aliased to Replace command
619 Replace(append(args, "-a"))
622 // RunShellCommand executes a shell command and returns the output/error
623 func RunShellCommand(input string) (string, error) {
624 inputCmd := SplitCommandArgs(input)[0]
625 args := SplitCommandArgs(input)[1:]
627 cmd := exec.Command(inputCmd, args...)
628 outputBytes := &bytes.Buffer{}
629 cmd.Stdout = outputBytes
630 cmd.Stderr = outputBytes
632 err := cmd.Wait() // wait for command to finish
633 outstring := outputBytes.String()
634 return outstring, err
637 // HandleShellCommand runs the shell command
638 // The openTerm argument specifies whether a terminal should be opened (for viewing output
639 // or interacting with stdin)
640 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
641 inputCmd := SplitCommandArgs(input)[0]
643 // Simply run the command in the background and notify the user when it's done
644 messenger.Message("Running...")
646 output, err := RunShellCommand(input)
647 totalLines := strings.Split(output, "\n")
649 if len(totalLines) < 3 {
651 messenger.Message(inputCmd, " exited without error")
653 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
656 messenger.Message(output)
658 // We have to make sure to redraw
662 // Shut down the screen because we're going to interact directly with the shell
666 args := SplitCommandArgs(input)[1:]
668 // Set up everything for the command
669 var outputBuf bytes.Buffer
670 cmd := exec.Command(inputCmd, args...)
672 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
673 cmd.Stderr = os.Stderr
675 // This is a trap for Ctrl-C so that it doesn't kill micro
676 // Instead we trap Ctrl-C to kill the program we're running
677 c := make(chan os.Signal, 1)
678 signal.Notify(c, os.Interrupt)
688 output := outputBuf.String()
694 // This is just so we don't return right away and let the user press enter to return
698 // Start the screen back up
706 // HandleCommand handles input from the user
707 func HandleCommand(input string) {
708 args := SplitCommandArgs(input)
711 if _, ok := commands[inputCmd]; !ok {
712 messenger.Error("Unknown command ", inputCmd)
714 commands[inputCmd].action(args[1:])