12 humanize "github.com/dustin/go-humanize"
13 "github.com/zyedidia/micro/cmd/micro/shellwords"
16 // A Command contains a action (a function to call) as well as information about how to autocomplete the command
19 completions []Completion
22 // A StrCommand is similar to a command but keeps the name of the action
23 type StrCommand struct {
25 completions []Completion
28 var commands map[string]Command
30 var commandActions map[string]func([]string)
33 commandActions = map[string]func([]string){
43 "ReplaceAll": ReplaceAll,
49 "ToggleLog": ToggleLog,
55 "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, OptionValueCompletion}},
95 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
96 "showkey": {"ShowKey", []Completion{NoCompletion}},
97 "bind": {"Bind", []Completion{NoCompletion}},
98 "run": {"Run", []Completion{NoCompletion}},
99 "quit": {"Quit", []Completion{NoCompletion}},
100 "save": {"Save", []Completion{NoCompletion}},
101 "replace": {"Replace", []Completion{NoCompletion}},
102 "replaceall": {"ReplaceAll", []Completion{NoCompletion}},
103 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
104 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
105 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
106 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
107 "eval": {"Eval", []Completion{NoCompletion}},
108 "log": {"ToggleLog", []Completion{NoCompletion}},
109 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
110 "reload": {"Reload", []Completion{NoCompletion}},
111 "cd": {"Cd", []Completion{FileCompletion}},
112 "pwd": {"Pwd", []Completion{NoCompletion}},
113 "open": {"Open", []Completion{FileCompletion}},
114 "tabswitch": {"TabSwitch", []Completion{NoCompletion}},
115 "term": {"Term", []Completion{NoCompletion}},
116 "memusage": {"MemUsage", []Completion{NoCompletion}},
117 "retab": {"Retab", []Completion{NoCompletion}},
118 "raw": {"Raw", []Completion{NoCompletion}},
122 // CommandEditAction returns a bindable function that opens a prompt with
123 // the given string and executes the command when the user presses
125 func CommandEditAction(prompt string) func(*View, bool) bool {
126 return func(v *View, usePlugin bool) bool {
127 input, canceled := messenger.Prompt("> ", prompt, "Command", CommandCompletion)
135 // CommandAction returns a bindable function which executes the
137 func CommandAction(cmd string) func(*View, bool) bool {
138 return func(v *View, usePlugin bool) bool {
144 // PluginCmd installs, removes, updates, lists, or searches for given plugins
145 func PluginCmd(args []string) {
149 installedVersions := GetInstalledVersions(false)
150 for _, plugin := range args[1:] {
151 pp := GetAllPluginPackages().Get(plugin)
153 messenger.Error("Unknown plugin \"" + plugin + "\"")
154 } else if err := pp.IsInstallable(); err != nil {
155 messenger.Error("Error installing ", plugin, ": ", err)
157 for _, installed := range installedVersions {
158 if pp.Name == installed.pack.Name {
159 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
160 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
162 messenger.Error(pp.Name, " is already installed")
171 for _, plugin := range args[1:] {
172 // check if the plugin exists.
173 if _, ok := loadedPlugins[plugin]; ok {
174 UninstallPlugin(plugin)
175 removed += plugin + " "
179 if !IsSpaces([]byte(removed)) {
180 messenger.Message("Removed ", removed)
182 messenger.Error("The requested plugins do not exist")
185 UpdatePlugins(args[1:])
187 plugins := GetInstalledVersions(false)
188 messenger.AddLog("----------------")
189 messenger.AddLog("The following plugins are currently installed:\n")
190 for _, p := range plugins {
191 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
193 messenger.AddLog("----------------")
194 if len(plugins) > 0 {
195 if CurView().Type != vtLog {
196 ToggleLog([]string{})
200 plugins := SearchPlugin(args[1:])
201 messenger.Message(len(plugins), " plugins found")
202 for _, p := range plugins {
203 messenger.AddLog("----------------")
204 messenger.AddLog(p.String())
206 messenger.AddLog("----------------")
207 if len(plugins) > 0 {
208 if CurView().Type != vtLog {
209 ToggleLog([]string{})
213 packages := GetAllPluginPackages()
214 messenger.AddLog("Available Plugins:")
215 for _, pkg := range packages {
216 messenger.AddLog(pkg.Name)
218 if CurView().Type != vtLog {
219 ToggleLog([]string{})
223 messenger.Error("Not enough arguments")
227 // Retab changes all spaces to tabs or all tabs to spaces
228 // depending on the user's settings
229 func Retab(args []string) {
230 CurView().Retab(true)
233 // Raw opens a new raw view which displays the escape sequences micro
234 // is receiving in real-time
235 func Raw(args []string) {
236 buf := NewBufferFromString("", "Raw events")
239 view.Buf.Insert(view.Cursor.Loc, "Warning: Showing raw event escape codes\n")
240 view.Buf.Insert(view.Cursor.Loc, "Use CtrlQ to exit\n")
242 tab := NewTabFromView(view)
243 tab.SetNum(len(tabs))
244 tabs = append(tabs, tab)
245 curTab = len(tabs) - 1
247 for _, t := range tabs {
248 for _, v := range t.views {
255 // TabSwitch switches to a given tab either by name or by number
256 func TabSwitch(args []string) {
258 num, err := strconv.Atoi(args[0])
260 // Check for tab with this name
263 for _, t := range tabs {
264 v := t.views[t.CurView]
265 if v.Buf.GetName() == args[0] {
271 messenger.Error("Could not find tab: ", err)
275 if num >= 0 && num < len(tabs) {
278 messenger.Error("Invalid tab index")
284 // Cd changes the current working directory
285 func Cd(args []string) {
287 path := ReplaceHome(args[0])
288 err := os.Chdir(path)
290 messenger.Error("Error with cd: ", err)
294 for _, tab := range tabs {
295 for _, view := range tab.views {
296 if len(view.Buf.name) == 0 {
300 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
301 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
302 view.Buf.Path = view.Buf.AbsPath
309 // MemUsage prints micro's memory usage
310 // Alloc shows how many bytes are currently in use
311 // Sys shows how many bytes have been requested from the operating system
312 // NumGC shows how many times the GC has been run
313 // Note that Go commonly reserves more memory from the OS than is currently in-use/required
314 // Additionally, even if Go returns memory to the OS, the OS does not always claim it because
315 // there may be plenty of memory to spare
316 func MemUsage(args []string) {
317 var mem runtime.MemStats
318 runtime.ReadMemStats(&mem)
320 messenger.Message(fmt.Sprintf("Alloc: %v, Sys: %v, NumGC: %v", humanize.Bytes(mem.Alloc), humanize.Bytes(mem.Sys), mem.NumGC))
323 // Pwd prints the current working directory
324 func Pwd(args []string) {
325 wd, err := os.Getwd()
327 messenger.Message(err.Error())
329 messenger.Message(wd)
333 // Open opens a new buffer with a given filename
334 func Open(args []string) {
337 // the filename might or might not be quoted, so unquote first then join the strings.
338 args, err := shellwords.Split(filename)
340 messenger.Error("Error parsing args ", err)
343 filename = strings.Join(args, " ")
345 CurView().Open(filename)
347 messenger.Error("No filename")
351 // ToggleLog toggles the log view
352 func ToggleLog(args []string) {
353 buffer := messenger.getBuffer()
354 if CurView().Type != vtLog {
355 CurView().HSplit(buffer)
356 CurView().Type = vtLog
358 buffer.Cursor.Loc = buffer.Start()
360 buffer.Cursor.Loc = buffer.End()
367 // Reload reloads all files (syntax files, colorschemes...)
368 func Reload(args []string) {
372 // Help tries to open the given help page in a horizontal split
373 func Help(args []string) {
375 // Open the default help if the user just typed "> help"
376 CurView().openHelp("help")
379 if FindRuntimeFile(RTHelp, helpPage) != nil {
380 CurView().openHelp(helpPage)
382 messenger.Error("Sorry, no help for ", helpPage)
387 // VSplit opens a vertical split with file given in the first argument
388 // If no file is given, it opens an empty buffer in a new split
389 func VSplit(args []string) {
391 CurView().VSplit(NewBufferFromString("", ""))
393 buf, err := NewBufferFromFile(args[0])
398 CurView().VSplit(buf)
402 // HSplit opens a horizontal split with file given in the first argument
403 // If no file is given, it opens an empty buffer in a new split
404 func HSplit(args []string) {
406 CurView().HSplit(NewBufferFromString("", ""))
408 buf, err := NewBufferFromFile(args[0])
413 CurView().HSplit(buf)
417 // Eval evaluates a lua expression
418 func Eval(args []string) {
420 err := L.DoString(args[0])
425 messenger.Error("Not enough arguments")
429 // NewTab opens the given file in a new tab
430 func NewTab(args []string) {
432 CurView().AddTab(true)
434 buf, err := NewBufferFromFile(args[0])
440 tab := NewTabFromView(NewView(buf))
441 tab.SetNum(len(tabs))
442 tabs = append(tabs, tab)
443 curTab = len(tabs) - 1
445 for _, t := range tabs {
446 for _, v := range t.views {
454 // Set sets an option
455 func Set(args []string) {
457 messenger.Error("Not enough arguments")
464 SetOptionAndSettings(option, value)
467 // SetLocal sets an option local to the buffer
468 func SetLocal(args []string) {
470 messenger.Error("Not enough arguments")
477 err := SetLocalOption(option, value, CurView())
479 messenger.Error(err.Error())
483 // Show shows the value of the given option
484 func Show(args []string) {
486 messenger.Error("Please provide an option to show")
490 option := GetOption(args[0])
493 messenger.Error(args[0], " is not a valid option")
497 messenger.Message(option)
500 // ShowKey displays the action that a key is bound to
501 func ShowKey(args []string) {
503 messenger.Error("Please provide a key to show")
507 if action, ok := bindingsStr[args[0]]; ok {
508 messenger.Message(action)
510 messenger.Message(args[0], " has no binding")
514 // Bind creates a new keybinding
515 func Bind(args []string) {
517 messenger.Error("Not enough arguments")
520 BindKey(args[0], args[1])
523 // Run runs a shell command in the background
524 func Run(args []string) {
525 // Run a shell command in the background (openTerm is false)
526 HandleShellCommand(shellwords.Join(args...), false, true)
529 // Quit closes the main view
530 func Quit(args []string) {
531 // Close the main view
535 // Save saves the buffer in the main view
536 func Save(args []string) {
538 // Save the main view
541 CurView().Buf.SaveAs(args[0])
545 // Replace runs search and replace
546 func Replace(args []string) {
547 if len(args) < 2 || len(args) > 4 {
548 // We need to find both a search and replace expression
549 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
557 for _, arg := range args[2:] {
564 messenger.Error("Invalid flag: " + arg)
570 search := string(args[0])
573 search = regexp.QuoteMeta(search)
576 replace := string(args[1])
578 regex, err := regexp.Compile("(?m)" + search)
580 // There was an error with the user's regex
581 messenger.Error(err.Error())
588 replaceAll := func() {
590 deltaXOffset := Count(replace) - Count(search)
591 for i := 0; i < view.Buf.LinesNum(); i++ {
592 matches := regex.FindAllIndex(view.Buf.lines[i].data, -1)
593 str := string(view.Buf.lines[i].data)
597 for _, m := range matches {
598 from := Loc{runePos(m[0], str) + xOffset, i}
599 to := Loc{runePos(m[1], str) + xOffset, i}
601 xOffset += deltaXOffset
603 deltas = append(deltas, Delta{replace, from, to})
608 view.Buf.MultipleReplace(deltas)
615 // The 'check' flag was used
616 Search(search, view, true)
617 if !view.Cursor.HasSelection() {
622 choice, canceled := messenger.LetterPrompt("Perform replacement? (y,n,a)", 'y', 'n', 'a')
624 if view.Cursor.HasSelection() {
625 view.Cursor.Loc = view.Cursor.CurSelection[0]
626 view.Cursor.ResetSelection()
630 } else if choice == 'a' {
631 if view.Cursor.HasSelection() {
632 view.Cursor.Loc = view.Cursor.CurSelection[0]
633 view.Cursor.ResetSelection()
638 } else if choice == 'y' {
639 view.Cursor.DeleteSelection()
640 view.Buf.Insert(view.Cursor.Loc, replace)
641 view.Cursor.ResetSelection()
645 if view.Cursor.HasSelection() {
646 searchStart = view.Cursor.CurSelection[1]
648 searchStart = view.Cursor.Loc
652 view.Cursor.Relocate()
655 messenger.Message("Replaced ", found, " occurrences of ", search)
656 } else if found == 1 {
657 messenger.Message("Replaced ", found, " occurrence of ", search)
659 messenger.Message("Nothing matched ", search)
663 // ReplaceAll replaces search term all at once
664 func ReplaceAll(args []string) {
665 // aliased to Replace command
666 Replace(append(args, "-a"))
669 // Term opens a terminal in the current view
670 func Term(args []string) {
673 err = CurView().StartTerminal([]string{os.Getenv("SHELL"), "-i"}, true, false, "")
675 err = CurView().StartTerminal(args, true, false, "")
682 // HandleCommand handles input from the user
683 func HandleCommand(input string) {
684 args, err := shellwords.Split(input)
686 messenger.Error("Error parsing args ", err)
692 if _, ok := commands[inputCmd]; !ok {
693 messenger.Error("Unknown command ", inputCmd)
695 commands[inputCmd].action(args[1:])