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){
51 "ToggleLog": ToggleLog,
57 "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, NoCompletion}},
93 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
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 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
101 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
102 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
103 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
104 "eval": {"Eval", []Completion{NoCompletion}},
105 "log": {"ToggleLog", []Completion{NoCompletion}},
106 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
107 "reload": {"Reload", []Completion{NoCompletion}},
108 "cd": {"Cd", []Completion{FileCompletion}},
109 "pwd": {"Pwd", []Completion{NoCompletion}},
110 "open": {"Open", []Completion{FileCompletion}},
111 "tabswitch": {"TabSwitch", []Completion{NoCompletion}},
112 "memusage": {"MemUsage", []Completion{NoCompletion}},
116 // PluginCmd installs, removes, updates, lists, or searches for given plugins
117 func PluginCmd(args []string) {
121 installedVersions := GetInstalledVersions(false)
122 for _, plugin := range args[1:] {
123 pp := GetAllPluginPackages().Get(plugin)
125 messenger.Error("Unknown plugin \"" + plugin + "\"")
126 } else if err := pp.IsInstallable(); err != nil {
127 messenger.Error("Error installing ", plugin, ": ", err)
129 for _, installed := range installedVersions {
130 if pp.Name == installed.pack.Name {
131 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
132 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
134 messenger.Error(pp.Name, " is already installed")
143 for _, plugin := range args[1:] {
144 // check if the plugin exists.
145 if _, ok := loadedPlugins[plugin]; ok {
146 UninstallPlugin(plugin)
147 removed += plugin + " "
151 if !IsSpaces(removed) {
152 messenger.Message("Removed ", removed)
154 messenger.Error("The requested plugins do not exist")
157 UpdatePlugins(args[1:])
159 plugins := GetInstalledVersions(false)
160 messenger.AddLog("----------------")
161 messenger.AddLog("The following plugins are currently installed:\n")
162 for _, p := range plugins {
163 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
165 messenger.AddLog("----------------")
166 if len(plugins) > 0 {
167 if CurView().Type != vtLog {
168 ToggleLog([]string{})
172 plugins := SearchPlugin(args[1:])
173 messenger.Message(len(plugins), " plugins found")
174 for _, p := range plugins {
175 messenger.AddLog("----------------")
176 messenger.AddLog(p.String())
178 messenger.AddLog("----------------")
179 if len(plugins) > 0 {
180 if CurView().Type != vtLog {
181 ToggleLog([]string{})
185 packages := GetAllPluginPackages()
186 messenger.AddLog("Available Plugins:")
187 for _, pkg := range packages {
188 messenger.AddLog(pkg.Name)
190 if CurView().Type != vtLog {
191 ToggleLog([]string{})
195 messenger.Error("Not enough arguments")
199 // TabSwitch switches to a given tab either by name or by number
200 func TabSwitch(args []string) {
202 num, err := strconv.Atoi(args[0])
204 // Check for tab with this name
207 for _, t := range tabs {
208 v := t.views[t.CurView]
209 if v.Buf.GetName() == args[0] {
215 messenger.Error("Could not find tab: ", err)
219 if num >= 0 && num < len(tabs) {
222 messenger.Error("Invalid tab index")
228 // Cd changes the current working directory
229 func Cd(args []string) {
231 home, _ := homedir.Dir()
232 path := strings.Replace(args[0], "~", home, 1)
234 for _, tab := range tabs {
235 for _, view := range tab.views {
237 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
238 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
239 view.Buf.Path = view.Buf.AbsPath
246 // MemUsage prints micro's memory usage
247 // Alloc shows how many bytes are currently in use
248 // Sys shows how many bytes have been requested from the operating system
249 // NumGC shows how many times the GC has been run
250 // Note that Go commonly reserves more memory from the OS than is currently in-use/required
251 // Additionally, even if Go returns memory to the OS, the OS does not always claim it because
252 // there may be plenty of memory to spare
253 func MemUsage(args []string) {
254 var mem runtime.MemStats
255 runtime.ReadMemStats(&mem)
257 messenger.Message(fmt.Sprintf("Alloc: %v, Sys: %v, NumGC: %v", humanize.Bytes(mem.Alloc), humanize.Bytes(mem.Sys), mem.NumGC))
260 // Pwd prints the current working directory
261 func Pwd(args []string) {
262 wd, err := os.Getwd()
264 messenger.Message(err.Error())
266 messenger.Message(wd)
270 // Open opens a new buffer with a given filename
271 func Open(args []string) {
274 // the filename might or might not be quoted, so unquote first then join the strings.
275 filename = strings.Join(SplitCommandArgs(filename), " ")
277 CurView().Open(filename)
279 messenger.Error("No filename")
283 // ToggleLog toggles the log view
284 func ToggleLog(args []string) {
285 buffer := messenger.getBuffer()
286 if CurView().Type != vtLog {
287 CurView().HSplit(buffer)
288 CurView().Type = vtLog
290 buffer.Cursor.Loc = buffer.Start()
292 buffer.Cursor.Loc = buffer.End()
299 // Reload reloads all files (syntax files, colorschemes...)
300 func Reload(args []string) {
304 // Help tries to open the given help page in a horizontal split
305 func Help(args []string) {
307 // Open the default help if the user just typed "> help"
308 CurView().openHelp("help")
311 if FindRuntimeFile(RTHelp, helpPage) != nil {
312 CurView().openHelp(helpPage)
314 messenger.Error("Sorry, no help for ", helpPage)
319 // VSplit opens a vertical split with file given in the first argument
320 // If no file is given, it opens an empty buffer in a new split
321 func VSplit(args []string) {
323 CurView().VSplit(NewBuffer(strings.NewReader(""), ""))
326 home, _ := homedir.Dir()
327 filename = strings.Replace(filename, "~", home, 1)
328 file, err := os.Open(filename)
333 // File does not exist -- create an empty buffer with that name
334 buf = NewBuffer(strings.NewReader(""), filename)
336 buf = NewBuffer(file, filename)
338 CurView().VSplit(buf)
342 // HSplit opens a horizontal split with file given in the first argument
343 // If no file is given, it opens an empty buffer in a new split
344 func HSplit(args []string) {
346 CurView().HSplit(NewBuffer(strings.NewReader(""), ""))
349 home, _ := homedir.Dir()
350 filename = strings.Replace(filename, "~", home, 1)
351 file, err := os.Open(filename)
356 // File does not exist -- create an empty buffer with that name
357 buf = NewBuffer(strings.NewReader(""), filename)
359 buf = NewBuffer(file, filename)
361 CurView().HSplit(buf)
365 // Eval evaluates a lua expression
366 func Eval(args []string) {
368 err := L.DoString(args[0])
373 messenger.Error("Not enough arguments")
377 // NewTab opens the given file in a new tab
378 func NewTab(args []string) {
380 CurView().AddTab(true)
383 home, _ := homedir.Dir()
384 filename = strings.Replace(filename, "~", home, 1)
385 file, _ := os.Open(filename)
388 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
389 tab.SetNum(len(tabs))
390 tabs = append(tabs, tab)
391 curTab = len(tabs) - 1
393 for _, t := range tabs {
394 for _, v := range t.views {
402 // Set sets an option
403 func Set(args []string) {
405 messenger.Error("Not enough arguments")
412 SetOptionAndSettings(option, value)
415 // SetLocal sets an option local to the buffer
416 func SetLocal(args []string) {
418 messenger.Error("Not enough arguments")
425 err := SetLocalOption(option, value, CurView())
427 messenger.Error(err.Error())
431 // Show shows the value of the given option
432 func Show(args []string) {
434 messenger.Error("Please provide an option to show")
438 option := GetOption(args[0])
441 messenger.Error(args[0], " is not a valid option")
445 messenger.Message(option)
448 // Bind creates a new keybinding
449 func Bind(args []string) {
451 messenger.Error("Not enough arguments")
454 BindKey(args[0], args[1])
457 // Run runs a shell command in the background
458 func Run(args []string) {
459 // Run a shell command in the background (openTerm is false)
460 HandleShellCommand(JoinCommandArgs(args...), false, true)
463 // Quit closes the main view
464 func Quit(args []string) {
465 // Close the main view
469 // Save saves the buffer in the main view
470 func Save(args []string) {
472 // Save the main view
475 CurView().Buf.SaveAs(args[0])
479 // Replace runs search and replace
480 func Replace(args []string) {
482 // We need to find both a search and replace expression
483 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
489 // The user included some flags
493 search := string(args[0])
494 replace := string(args[1])
496 regex, err := regexp.Compile("(?m)" + search)
498 // There was an error with the user's regex
499 messenger.Error(err.Error())
506 if strings.Contains(flags, "c") {
508 // The 'check' flag was used
509 Search(search, view, true)
510 if !view.Cursor.HasSelection() {
515 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
517 if view.Cursor.HasSelection() {
518 view.Cursor.Loc = view.Cursor.CurSelection[0]
519 view.Cursor.ResetSelection()
525 view.Cursor.DeleteSelection()
526 view.Buf.Insert(view.Cursor.Loc, replace)
527 view.Cursor.ResetSelection()
531 if view.Cursor.HasSelection() {
532 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
534 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
540 bufStr := view.Buf.String()
541 matches := regex.FindAllStringIndex(bufStr, -1)
542 if matches != nil && len(matches) > 0 {
543 prevMatchCount := runePos(matches[0][0], bufStr)
544 searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
545 from := FromCharPos(matches[0][0], view.Buf)
546 to := from.Move(searchCount, view.Buf)
547 adjust := Count(replace) - searchCount
548 view.Buf.Replace(from, to, replace)
550 if len(matches) > 1 {
551 for _, match := range matches[1:] {
553 matchCount := runePos(match[0], bufStr)
554 searchCount = runePos(match[1], bufStr) - matchCount
555 from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
556 to = from.Move(searchCount, view.Buf)
557 view.Buf.Replace(from, to, replace)
558 prevMatchCount = matchCount
559 adjust = Count(replace) - searchCount
564 view.Cursor.Relocate()
567 messenger.Message("Replaced ", found, " occurrences of ", search)
568 } else if found == 1 {
569 messenger.Message("Replaced ", found, " occurrence of ", search)
571 messenger.Message("Nothing matched ", search)
575 // RunShellCommand executes a shell command and returns the output/error
576 func RunShellCommand(input string) (string, error) {
577 inputCmd := SplitCommandArgs(input)[0]
578 args := SplitCommandArgs(input)[1:]
580 cmd := exec.Command(inputCmd, args...)
581 outputBytes := &bytes.Buffer{}
582 cmd.Stdout = outputBytes
583 cmd.Stderr = outputBytes
585 err := cmd.Wait() // wait for command to finish
586 outstring := outputBytes.String()
587 return outstring, err
590 // HandleShellCommand runs the shell command
591 // The openTerm argument specifies whether a terminal should be opened (for viewing output
592 // or interacting with stdin)
593 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
594 inputCmd := SplitCommandArgs(input)[0]
596 // Simply run the command in the background and notify the user when it's done
597 messenger.Message("Running...")
599 output, err := RunShellCommand(input)
600 totalLines := strings.Split(output, "\n")
602 if len(totalLines) < 3 {
604 messenger.Message(inputCmd, " exited without error")
606 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
609 messenger.Message(output)
611 // We have to make sure to redraw
615 // Shut down the screen because we're going to interact directly with the shell
619 args := SplitCommandArgs(input)[1:]
621 // Set up everything for the command
622 var outputBuf bytes.Buffer
623 cmd := exec.Command(inputCmd, args...)
625 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
626 cmd.Stderr = os.Stderr
628 // This is a trap for Ctrl-C so that it doesn't kill micro
629 // Instead we trap Ctrl-C to kill the program we're running
630 c := make(chan os.Signal, 1)
631 signal.Notify(c, os.Interrupt)
641 output := outputBuf.String()
647 // This is just so we don't return right away and let the user press enter to return
651 // Start the screen back up
659 // HandleCommand handles input from the user
660 func HandleCommand(input string) {
661 args := SplitCommandArgs(input)
664 if _, ok := commands[inputCmd]; !ok {
665 messenger.Error("Unknown command ", inputCmd)
667 commands[inputCmd].action(args[1:])