15 humanize "github.com/dustin/go-humanize"
18 // A Command contains a action (a function to call) as well as information about how to autocomplete the command
21 completions []Completion
24 // A StrCommand is similar to a command but keeps the name of the action
25 type StrCommand struct {
27 completions []Completion
30 var commands map[string]Command
32 var commandActions map[string]func([]string)
35 commandActions = map[string]func([]string){
44 "ReplaceAll": ReplaceAll,
50 "ToggleLog": ToggleLog,
56 "TabSwitch": TabSwitch,
62 // InitCommands initializes the default commands
64 commands = make(map[string]Command)
66 defaults := DefaultCommands()
67 parseCommands(defaults)
70 func parseCommands(userCommands map[string]StrCommand) {
71 for k, v := range userCommands {
72 MakeCommand(k, v.action, v.completions...)
76 // MakeCommand is a function to easily create new commands
77 // This can be called by plugins in Lua so that plugins can define their own commands
78 func MakeCommand(name, function string, completions ...Completion) {
79 action := commandActions[function]
80 if _, ok := commandActions[function]; !ok {
81 // If the user seems to be binding a function that doesn't exist
82 // We hope that it's a lua function that exists and bind it to that
83 action = LuaFunctionCommand(function)
86 commands[name] = Command{action, completions}
89 // DefaultCommands returns a map containing micro's default commands
90 func DefaultCommands() map[string]StrCommand {
91 return map[string]StrCommand{
92 "set": {"Set", []Completion{OptionCompletion, OptionValueCompletion}},
93 "setlocal": {"SetLocal", []Completion{OptionCompletion, OptionValueCompletion}},
94 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
95 "bind": {"Bind", []Completion{NoCompletion}},
96 "run": {"Run", []Completion{NoCompletion}},
97 "quit": {"Quit", []Completion{NoCompletion}},
98 "save": {"Save", []Completion{NoCompletion}},
99 "replace": {"Replace", []Completion{NoCompletion}},
100 "replaceall": {"ReplaceAll", []Completion{NoCompletion}},
101 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
102 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
103 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
104 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
105 "eval": {"Eval", []Completion{NoCompletion}},
106 "log": {"ToggleLog", []Completion{NoCompletion}},
107 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
108 "reload": {"Reload", []Completion{NoCompletion}},
109 "cd": {"Cd", []Completion{FileCompletion}},
110 "pwd": {"Pwd", []Completion{NoCompletion}},
111 "open": {"Open", []Completion{FileCompletion}},
112 "tabswitch": {"TabSwitch", []Completion{NoCompletion}},
113 "memusage": {"MemUsage", []Completion{NoCompletion}},
114 "retab": {"Retab", []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 func Retab(args []string) {
202 CurView().Retab(true)
205 // TabSwitch switches to a given tab either by name or by number
206 func TabSwitch(args []string) {
208 num, err := strconv.Atoi(args[0])
210 // Check for tab with this name
213 for _, t := range tabs {
214 v := t.views[t.CurView]
215 if v.Buf.GetName() == args[0] {
221 messenger.Error("Could not find tab: ", err)
225 if num >= 0 && num < len(tabs) {
228 messenger.Error("Invalid tab index")
234 // Cd changes the current working directory
235 func Cd(args []string) {
237 path := ReplaceHome(args[0])
238 err := os.Chdir(path)
240 messenger.Error("Error with cd: ", err)
244 for _, tab := range tabs {
245 for _, view := range tab.views {
246 if len(view.Buf.name) == 0 {
250 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
251 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
252 view.Buf.Path = view.Buf.AbsPath
259 // MemUsage prints micro's memory usage
260 // Alloc shows how many bytes are currently in use
261 // Sys shows how many bytes have been requested from the operating system
262 // NumGC shows how many times the GC has been run
263 // Note that Go commonly reserves more memory from the OS than is currently in-use/required
264 // Additionally, even if Go returns memory to the OS, the OS does not always claim it because
265 // there may be plenty of memory to spare
266 func MemUsage(args []string) {
267 var mem runtime.MemStats
268 runtime.ReadMemStats(&mem)
270 messenger.Message(fmt.Sprintf("Alloc: %v, Sys: %v, NumGC: %v", humanize.Bytes(mem.Alloc), humanize.Bytes(mem.Sys), mem.NumGC))
273 // Pwd prints the current working directory
274 func Pwd(args []string) {
275 wd, err := os.Getwd()
277 messenger.Message(err.Error())
279 messenger.Message(wd)
283 // Open opens a new buffer with a given filename
284 func Open(args []string) {
287 // the filename might or might not be quoted, so unquote first then join the strings.
288 args, err := SplitCommandArgs(filename)
290 messenger.Error("Error parsing args ", err)
293 filename = strings.Join(args, " ")
295 CurView().Open(filename)
297 messenger.Error("No filename")
301 // ToggleLog toggles the log view
302 func ToggleLog(args []string) {
303 buffer := messenger.getBuffer()
304 if CurView().Type != vtLog {
305 CurView().HSplit(buffer)
306 CurView().Type = vtLog
308 buffer.Cursor.Loc = buffer.Start()
310 buffer.Cursor.Loc = buffer.End()
317 // Reload reloads all files (syntax files, colorschemes...)
318 func Reload(args []string) {
322 // Help tries to open the given help page in a horizontal split
323 func Help(args []string) {
325 // Open the default help if the user just typed "> help"
326 CurView().openHelp("help")
329 if FindRuntimeFile(RTHelp, helpPage) != nil {
330 CurView().openHelp(helpPage)
332 messenger.Error("Sorry, no help for ", helpPage)
337 // VSplit opens a vertical split with file given in the first argument
338 // If no file is given, it opens an empty buffer in a new split
339 func VSplit(args []string) {
341 CurView().VSplit(NewBufferFromString("", ""))
344 filename = ReplaceHome(filename)
345 file, err := os.Open(filename)
346 fileInfo, _ := os.Stat(filename)
348 if err == nil && fileInfo.IsDir() {
349 messenger.Error(filename, " is a directory")
357 // File does not exist -- create an empty buffer with that name
358 buf = NewBufferFromString("", filename)
360 buf = NewBuffer(file, FSize(file), filename)
362 CurView().VSplit(buf)
366 // HSplit opens a horizontal split with file given in the first argument
367 // If no file is given, it opens an empty buffer in a new split
368 func HSplit(args []string) {
370 CurView().HSplit(NewBufferFromString("", ""))
373 filename = ReplaceHome(filename)
374 file, err := os.Open(filename)
375 fileInfo, _ := os.Stat(filename)
377 if err == nil && fileInfo.IsDir() {
378 messenger.Error(filename, " is a directory")
386 // File does not exist -- create an empty buffer with that name
387 buf = NewBufferFromString("", filename)
389 buf = NewBuffer(file, FSize(file), filename)
391 CurView().HSplit(buf)
395 // Eval evaluates a lua expression
396 func Eval(args []string) {
398 err := L.DoString(args[0])
403 messenger.Error("Not enough arguments")
407 // NewTab opens the given file in a new tab
408 func NewTab(args []string) {
410 CurView().AddTab(true)
413 filename = ReplaceHome(filename)
414 file, err := os.Open(filename)
415 fileInfo, _ := os.Stat(filename)
417 if err == nil && fileInfo.IsDir() {
418 messenger.Error(filename, " is a directory")
426 buf = NewBufferFromString("", filename)
428 buf = NewBuffer(file, FSize(file), filename)
431 tab := NewTabFromView(NewView(buf))
432 tab.SetNum(len(tabs))
433 tabs = append(tabs, tab)
434 curTab = len(tabs) - 1
436 for _, t := range tabs {
437 for _, v := range t.views {
445 // Set sets an option
446 func Set(args []string) {
448 messenger.Error("Not enough arguments")
455 SetOptionAndSettings(option, value)
458 // SetLocal sets an option local to the buffer
459 func SetLocal(args []string) {
461 messenger.Error("Not enough arguments")
468 err := SetLocalOption(option, value, CurView())
470 messenger.Error(err.Error())
474 // Show shows the value of the given option
475 func Show(args []string) {
477 messenger.Error("Please provide an option to show")
481 option := GetOption(args[0])
484 messenger.Error(args[0], " is not a valid option")
488 messenger.Message(option)
491 // Bind creates a new keybinding
492 func Bind(args []string) {
494 messenger.Error("Not enough arguments")
497 BindKey(args[0], args[1])
500 // Run runs a shell command in the background
501 func Run(args []string) {
502 // Run a shell command in the background (openTerm is false)
503 HandleShellCommand(JoinCommandArgs(args...), false, true)
506 // Quit closes the main view
507 func Quit(args []string) {
508 // Close the main view
512 // Save saves the buffer in the main view
513 func Save(args []string) {
515 // Save the main view
518 CurView().Buf.SaveAs(args[0])
522 // Replace runs search and replace
523 func Replace(args []string) {
524 if len(args) < 2 || len(args) > 4 {
525 // We need to find both a search and replace expression
526 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
534 for _, arg := range args[2:] {
541 messenger.Error("Invalid flag: " + arg)
547 search := string(args[0])
550 search = regexp.QuoteMeta(search)
553 replace := string(args[1])
555 regex, err := regexp.Compile("(?m)" + search)
557 // There was an error with the user's regex
558 messenger.Error(err.Error())
565 replaceAll := func() {
567 deltaXOffset := Count(replace) - Count(search)
568 for i := 0; i < view.Buf.LinesNum(); i++ {
569 matches := regex.FindAllIndex(view.Buf.lines[i].data, -1)
570 str := string(view.Buf.lines[i].data)
574 for _, m := range matches {
575 from := Loc{runePos(m[0], str) + xOffset, i}
576 to := Loc{runePos(m[1], str) + xOffset, i}
578 xOffset += deltaXOffset
580 deltas = append(deltas, Delta{replace, from, to})
585 view.Buf.MultipleReplace(deltas)
592 // The 'check' flag was used
593 Search(search, view, true)
594 if !view.Cursor.HasSelection() {
599 choice, canceled := messenger.LetterPrompt("Perform replacement? (y,n,a)", 'y', 'n', 'a')
601 if view.Cursor.HasSelection() {
602 view.Cursor.Loc = view.Cursor.CurSelection[0]
603 view.Cursor.ResetSelection()
607 } else if choice == 'a' {
608 if view.Cursor.HasSelection() {
609 view.Cursor.Loc = view.Cursor.CurSelection[0]
610 view.Cursor.ResetSelection()
615 } else if choice == 'y' {
616 view.Cursor.DeleteSelection()
617 view.Buf.Insert(view.Cursor.Loc, replace)
618 view.Cursor.ResetSelection()
622 if view.Cursor.HasSelection() {
623 searchStart = view.Cursor.CurSelection[1]
625 searchStart = view.Cursor.Loc
629 view.Cursor.Relocate()
632 messenger.Message("Replaced ", found, " occurrences of ", search)
633 } else if found == 1 {
634 messenger.Message("Replaced ", found, " occurrence of ", search)
636 messenger.Message("Nothing matched ", search)
640 // ReplaceAll replaces search term all at once
641 func ReplaceAll(args []string) {
642 // aliased to Replace command
643 Replace(append(args, "-a"))
646 // RunShellCommand executes a shell command and returns the output/error
647 func RunShellCommand(input string) (string, error) {
648 args, err := SplitCommandArgs(input)
654 cmd := exec.Command(inputCmd, args[1:]...)
655 outputBytes := &bytes.Buffer{}
656 cmd.Stdout = outputBytes
657 cmd.Stderr = outputBytes
659 err = cmd.Wait() // wait for command to finish
660 outstring := outputBytes.String()
661 return outstring, err
664 // HandleShellCommand runs the shell command
665 // The openTerm argument specifies whether a terminal should be opened (for viewing output
666 // or interacting with stdin)
667 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
668 args, err := SplitCommandArgs(input)
674 // Simply run the command in the background and notify the user when it's done
675 messenger.Message("Running...")
677 output, err := RunShellCommand(input)
678 totalLines := strings.Split(output, "\n")
680 if len(totalLines) < 3 {
682 messenger.Message(inputCmd, " exited without error")
684 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
687 messenger.Message(output)
689 // We have to make sure to redraw
693 // Shut down the screen because we're going to interact directly with the shell
699 // Set up everything for the command
701 cmd := exec.Command(inputCmd, args...)
703 cmd.Stdout = os.Stdout
704 cmd.Stderr = os.Stderr
706 // This is a trap for Ctrl-C so that it doesn't kill micro
707 // Instead we trap Ctrl-C to kill the program we're running
708 c := make(chan os.Signal, 1)
709 signal.Notify(c, os.Interrupt)
724 // This is just so we don't return right away and let the user press enter to return
728 // Start the screen back up
736 // HandleCommand handles input from the user
737 func HandleCommand(input string) {
738 args, err := SplitCommandArgs(input)
740 messenger.Error("Error parsing args ", err)
746 if _, ok := commands[inputCmd]; !ok {
747 messenger.Error("Unknown command ", inputCmd)
749 commands[inputCmd].action(args[1:])