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)
329 fileInfo, _ := os.Stat(filename)
331 if err == nil && fileInfo.IsDir() {
332 messenger.Error(filename, " is a directory")
340 // File does not exist -- create an empty buffer with that name
341 buf = NewBuffer(strings.NewReader(""), filename)
343 buf = NewBuffer(file, filename)
345 CurView().VSplit(buf)
349 // HSplit opens a horizontal split with file given in the first argument
350 // If no file is given, it opens an empty buffer in a new split
351 func HSplit(args []string) {
353 CurView().HSplit(NewBuffer(strings.NewReader(""), ""))
356 home, _ := homedir.Dir()
357 filename = strings.Replace(filename, "~", home, 1)
358 file, err := os.Open(filename)
359 fileInfo, _ := os.Stat(filename)
361 if err == nil && fileInfo.IsDir() {
362 messenger.Error(filename, " is a directory")
370 // File does not exist -- create an empty buffer with that name
371 buf = NewBuffer(strings.NewReader(""), filename)
373 buf = NewBuffer(file, filename)
375 CurView().HSplit(buf)
379 // Eval evaluates a lua expression
380 func Eval(args []string) {
382 err := L.DoString(args[0])
387 messenger.Error("Not enough arguments")
391 // NewTab opens the given file in a new tab
392 func NewTab(args []string) {
394 CurView().AddTab(true)
397 home, _ := homedir.Dir()
398 filename = strings.Replace(filename, "~", home, 1)
399 file, err := os.Open(filename)
400 fileInfo, _ := os.Stat(filename)
402 if err == nil && fileInfo.IsDir() {
403 messenger.Error(filename, " is a directory")
411 buf = NewBuffer(strings.NewReader(""), filename)
413 buf = NewBuffer(file, filename)
416 tab := NewTabFromView(NewView(buf))
417 tab.SetNum(len(tabs))
418 tabs = append(tabs, tab)
419 curTab = len(tabs) - 1
421 for _, t := range tabs {
422 for _, v := range t.views {
430 // Set sets an option
431 func Set(args []string) {
433 messenger.Error("Not enough arguments")
440 SetOptionAndSettings(option, value)
443 // SetLocal sets an option local to the buffer
444 func SetLocal(args []string) {
446 messenger.Error("Not enough arguments")
453 err := SetLocalOption(option, value, CurView())
455 messenger.Error(err.Error())
459 // Show shows the value of the given option
460 func Show(args []string) {
462 messenger.Error("Please provide an option to show")
466 option := GetOption(args[0])
469 messenger.Error(args[0], " is not a valid option")
473 messenger.Message(option)
476 // Bind creates a new keybinding
477 func Bind(args []string) {
479 messenger.Error("Not enough arguments")
482 BindKey(args[0], args[1])
485 // Run runs a shell command in the background
486 func Run(args []string) {
487 // Run a shell command in the background (openTerm is false)
488 HandleShellCommand(JoinCommandArgs(args...), false, true)
491 // Quit closes the main view
492 func Quit(args []string) {
493 // Close the main view
497 // Save saves the buffer in the main view
498 func Save(args []string) {
500 // Save the main view
503 CurView().Buf.SaveAs(args[0])
507 // Replace runs search and replace
508 func Replace(args []string) {
510 // We need to find both a search and replace expression
511 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
517 // The user included some flags
521 search := string(args[0])
522 replace := string(args[1])
524 regex, err := regexp.Compile("(?m)" + search)
526 // There was an error with the user's regex
527 messenger.Error(err.Error())
534 if strings.Contains(flags, "c") {
536 // The 'check' flag was used
537 Search(search, view, true)
538 if !view.Cursor.HasSelection() {
543 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
545 if view.Cursor.HasSelection() {
546 view.Cursor.Loc = view.Cursor.CurSelection[0]
547 view.Cursor.ResetSelection()
553 view.Cursor.DeleteSelection()
554 view.Buf.Insert(view.Cursor.Loc, replace)
555 view.Cursor.ResetSelection()
559 if view.Cursor.HasSelection() {
560 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
562 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
568 bufStr := view.Buf.String()
569 matches := regex.FindAllStringIndex(bufStr, -1)
570 if matches != nil && len(matches) > 0 {
571 prevMatchCount := runePos(matches[0][0], bufStr)
572 searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
573 from := FromCharPos(matches[0][0], view.Buf)
574 to := from.Move(searchCount, view.Buf)
575 adjust := Count(replace) - searchCount
576 view.Buf.Replace(from, to, replace)
578 if len(matches) > 1 {
579 for _, match := range matches[1:] {
581 matchCount := runePos(match[0], bufStr)
582 searchCount = runePos(match[1], bufStr) - matchCount
583 from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
584 to = from.Move(searchCount, view.Buf)
585 view.Buf.Replace(from, to, replace)
586 prevMatchCount = matchCount
587 adjust = Count(replace) - searchCount
592 view.Cursor.Relocate()
595 messenger.Message("Replaced ", found, " occurrences of ", search)
596 } else if found == 1 {
597 messenger.Message("Replaced ", found, " occurrence of ", search)
599 messenger.Message("Nothing matched ", search)
603 // RunShellCommand executes a shell command and returns the output/error
604 func RunShellCommand(input string) (string, error) {
605 inputCmd := SplitCommandArgs(input)[0]
606 args := SplitCommandArgs(input)[1:]
608 cmd := exec.Command(inputCmd, args...)
609 outputBytes := &bytes.Buffer{}
610 cmd.Stdout = outputBytes
611 cmd.Stderr = outputBytes
613 err := cmd.Wait() // wait for command to finish
614 outstring := outputBytes.String()
615 return outstring, err
618 // HandleShellCommand runs the shell command
619 // The openTerm argument specifies whether a terminal should be opened (for viewing output
620 // or interacting with stdin)
621 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
622 inputCmd := SplitCommandArgs(input)[0]
624 // Simply run the command in the background and notify the user when it's done
625 messenger.Message("Running...")
627 output, err := RunShellCommand(input)
628 totalLines := strings.Split(output, "\n")
630 if len(totalLines) < 3 {
632 messenger.Message(inputCmd, " exited without error")
634 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
637 messenger.Message(output)
639 // We have to make sure to redraw
643 // Shut down the screen because we're going to interact directly with the shell
647 args := SplitCommandArgs(input)[1:]
649 // Set up everything for the command
650 var outputBuf bytes.Buffer
651 cmd := exec.Command(inputCmd, args...)
653 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
654 cmd.Stderr = os.Stderr
656 // This is a trap for Ctrl-C so that it doesn't kill micro
657 // Instead we trap Ctrl-C to kill the program we're running
658 c := make(chan os.Signal, 1)
659 signal.Notify(c, os.Interrupt)
669 output := outputBuf.String()
675 // This is just so we don't return right away and let the user press enter to return
679 // Start the screen back up
687 // HandleCommand handles input from the user
688 func HandleCommand(input string) {
689 args := SplitCommandArgs(input)
692 if _, ok := commands[inputCmd]; !ok {
693 messenger.Error("Unknown command ", inputCmd)
695 commands[inputCmd].action(args[1:])