14 "github.com/mitchellh/go-homedir"
19 completions []Completion
22 type StrCommand struct {
24 completions []Completion
27 var commands map[string]Command
29 var commandActions map[string]func([]string)
32 commandActions = map[string]func([]string){
46 "ToggleLog": ToggleLog,
55 // InitCommands initializes the default commands
57 commands = make(map[string]Command)
59 defaults := DefaultCommands()
60 parseCommands(defaults)
63 func parseCommands(userCommands map[string]StrCommand) {
64 for k, v := range userCommands {
65 MakeCommand(k, v.action, v.completions...)
69 // MakeCommand is a function to easily create new commands
70 // This can be called by plugins in Lua so that plugins can define their own commands
71 func MakeCommand(name, function string, completions ...Completion) {
72 action := commandActions[function]
73 if _, ok := commandActions[function]; !ok {
74 // If the user seems to be binding a function that doesn't exist
75 // We hope that it's a lua function that exists and bind it to that
76 action = LuaFunctionCommand(function)
79 commands[name] = Command{action, completions}
82 // DefaultCommands returns a map containing micro's default commands
83 func DefaultCommands() map[string]StrCommand {
84 return map[string]StrCommand{
85 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
86 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
87 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
88 "bind": {"Bind", []Completion{NoCompletion}},
89 "run": {"Run", []Completion{NoCompletion}},
90 "quit": {"Quit", []Completion{NoCompletion}},
91 "save": {"Save", []Completion{NoCompletion}},
92 "replace": {"Replace", []Completion{NoCompletion}},
93 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
94 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
95 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
96 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
97 "eval": {"Eval", []Completion{NoCompletion}},
98 "log": {"ToggleLog", []Completion{NoCompletion}},
99 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
100 "reload": {"Reload", []Completion{NoCompletion}},
101 "cd": {"Cd", []Completion{FileCompletion}},
102 "pwd": {"Pwd", []Completion{NoCompletion}},
103 "open": {"Open", []Completion{FileCompletion}},
107 // PluginCmd installs, removes, updates, lists, or searches for given plugins
108 func PluginCmd(args []string) {
112 installedVersions := GetInstalledVersions(false)
113 for _, plugin := range args[1:] {
114 pp := GetAllPluginPackages().Get(plugin)
116 messenger.Error("Unknown plugin \"" + plugin + "\"")
117 } else if err := pp.IsInstallable(); err != nil {
118 messenger.Error("Error installing ", plugin, ": ", err)
120 for _, installed := range installedVersions {
121 if pp.Name == installed.pack.Name {
122 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
123 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
125 messenger.Error(pp.Name, " is already installed")
134 for _, plugin := range args[1:] {
135 // check if the plugin exists.
136 if _, ok := loadedPlugins[plugin]; ok {
137 UninstallPlugin(plugin)
138 removed += plugin + " "
142 if !IsSpaces(removed) {
143 messenger.Message("Removed ", removed)
145 messenger.Error("The requested plugins do not exist")
148 UpdatePlugins(args[1:])
150 plugins := GetInstalledVersions(false)
151 messenger.AddLog("----------------")
152 messenger.AddLog("The following plugins are currently installed:\n")
153 for _, p := range plugins {
154 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
156 messenger.AddLog("----------------")
157 if len(plugins) > 0 {
158 if CurView().Type != vtLog {
159 ToggleLog([]string{})
163 plugins := SearchPlugin(args[1:])
164 messenger.Message(len(plugins), " plugins found")
165 for _, p := range plugins {
166 messenger.AddLog("----------------")
167 messenger.AddLog(p.String())
169 messenger.AddLog("----------------")
170 if len(plugins) > 0 {
171 if CurView().Type != vtLog {
172 ToggleLog([]string{})
176 packages := GetAllPluginPackages()
177 messenger.AddLog("Available Plugins:")
178 for _, pkg := range packages {
179 messenger.AddLog(pkg.Name)
181 if CurView().Type != vtLog {
182 ToggleLog([]string{})
186 messenger.Error("Not enough arguments")
190 func Cd(args []string) {
192 home, _ := homedir.Dir()
193 path := strings.Replace(args[0], "~", home, 1)
195 for _, tab := range tabs {
196 for _, view := range tab.views {
198 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
199 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
200 view.Buf.Path = view.Buf.AbsPath
207 func Pwd(args []string) {
208 wd, err := os.Getwd()
210 messenger.Message(err.Error())
212 messenger.Message(wd)
216 func Open(args []string) {
219 // the filename might or might not be quoted, so unquote first then join the strings.
220 filename = strings.Join(SplitCommandArgs(filename), " ")
222 CurView().Open(filename)
224 messenger.Error("No filename")
228 func ToggleLog(args []string) {
229 buffer := messenger.getBuffer()
230 if CurView().Type != vtLog {
231 CurView().HSplit(buffer)
232 CurView().Type = vtLog
234 buffer.Cursor.Loc = buffer.Start()
236 buffer.Cursor.Loc = buffer.End()
243 func Reload(args []string) {
247 // Help tries to open the given help page in a horizontal split
248 func Help(args []string) {
250 // Open the default help if the user just typed "> help"
251 CurView().openHelp("help")
254 if FindRuntimeFile(RTHelp, helpPage) != nil {
255 CurView().openHelp(helpPage)
257 messenger.Error("Sorry, no help for ", helpPage)
262 // VSplit opens a vertical split with file given in the first argument
263 // If no file is given, it opens an empty buffer in a new split
264 func VSplit(args []string) {
266 CurView().VSplit(NewBuffer(strings.NewReader(""), ""))
269 home, _ := homedir.Dir()
270 filename = strings.Replace(filename, "~", home, 1)
271 file, err := os.Open(filename)
276 // File does not exist -- create an empty buffer with that name
277 buf = NewBuffer(strings.NewReader(""), filename)
279 buf = NewBuffer(file, filename)
281 CurView().VSplit(buf)
285 // HSplit opens a horizontal split with file given in the first argument
286 // If no file is given, it opens an empty buffer in a new split
287 func HSplit(args []string) {
289 CurView().HSplit(NewBuffer(strings.NewReader(""), ""))
292 home, _ := homedir.Dir()
293 filename = strings.Replace(filename, "~", home, 1)
294 file, err := os.Open(filename)
299 // File does not exist -- create an empty buffer with that name
300 buf = NewBuffer(strings.NewReader(""), filename)
302 buf = NewBuffer(file, filename)
304 CurView().HSplit(buf)
308 // Eval evaluates a lua expression
309 func Eval(args []string) {
311 err := L.DoString(args[0])
316 messenger.Error("Not enough arguments")
320 // NewTab opens the given file in a new tab
321 func NewTab(args []string) {
323 CurView().AddTab(true)
326 home, _ := homedir.Dir()
327 filename = strings.Replace(filename, "~", home, 1)
328 file, _ := os.Open(filename)
331 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
332 tab.SetNum(len(tabs))
333 tabs = append(tabs, tab)
334 curTab = len(tabs) - 1
336 for _, t := range tabs {
337 for _, v := range t.views {
345 // Set sets an option
346 func Set(args []string) {
348 messenger.Error("Not enough arguments")
352 option := strings.TrimSpace(args[0])
353 value := strings.TrimSpace(args[1])
355 SetOptionAndSettings(option, value)
358 // SetLocal sets an option local to the buffer
359 func SetLocal(args []string) {
361 messenger.Error("Not enough arguments")
365 option := strings.TrimSpace(args[0])
366 value := strings.TrimSpace(args[1])
368 err := SetLocalOption(option, value, CurView())
370 messenger.Error(err.Error())
374 // Show shows the value of the given option
375 func Show(args []string) {
377 messenger.Error("Please provide an option to show")
381 option := GetOption(args[0])
384 messenger.Error(args[0], " is not a valid option")
388 messenger.Message(option)
391 // Bind creates a new keybinding
392 func Bind(args []string) {
394 messenger.Error("Not enough arguments")
397 BindKey(args[0], args[1])
400 // Run runs a shell command in the background
401 func Run(args []string) {
402 // Run a shell command in the background (openTerm is false)
403 HandleShellCommand(JoinCommandArgs(args...), false, true)
406 // Quit closes the main view
407 func Quit(args []string) {
408 // Close the main view
412 // Save saves the buffer in the main view
413 func Save(args []string) {
415 // Save the main view
418 CurView().Buf.SaveAs(args[0])
422 // Replace runs search and replace
423 func Replace(args []string) {
425 // We need to find both a search and replace expression
426 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
432 // The user included some flags
436 search := string(args[0])
437 replace := string(args[1])
439 regex, err := regexp.Compile("(?m)" + search)
441 // There was an error with the user's regex
442 messenger.Error(err.Error())
449 if strings.Contains(flags, "c") {
451 // The 'check' flag was used
452 Search(search, view, true)
453 if !view.Cursor.HasSelection() {
457 if view.Buf.Settings["syntax"].(bool) {
458 view.matches = Match(view)
461 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
463 if view.Cursor.HasSelection() {
464 view.Cursor.Loc = view.Cursor.CurSelection[0]
465 view.Cursor.ResetSelection()
471 view.Cursor.DeleteSelection()
472 view.Buf.Insert(view.Cursor.Loc, replace)
473 view.Cursor.ResetSelection()
477 if view.Cursor.HasSelection() {
478 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
480 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
486 bufStr := view.Buf.String()
487 matches := regex.FindAllStringIndex(bufStr, -1)
488 if matches != nil && len(matches) > 0 {
489 prevMatchCount := runePos(matches[0][0], bufStr)
490 searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
491 from := FromCharPos(matches[0][0], view.Buf)
492 to := from.Move(searchCount, view.Buf)
493 adjust := Count(replace) - searchCount
494 view.Buf.Replace(from, to, replace)
495 if len(matches) > 1 {
496 for _, match := range matches[1:] {
498 matchCount := runePos(match[0], bufStr)
499 searchCount = runePos(match[1], bufStr) - matchCount
500 from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
501 to = from.Move(searchCount, view.Buf)
502 view.Buf.Replace(from, to, replace)
503 prevMatchCount = matchCount
504 adjust = Count(replace) - searchCount
509 view.Cursor.Relocate()
512 messenger.Message("Replaced ", found, " occurrences of ", search)
513 } else if found == 1 {
514 messenger.Message("Replaced ", found, " occurrence of ", search)
516 messenger.Message("Nothing matched ", search)
520 // RunShellCommand executes a shell command and returns the output/error
521 func RunShellCommand(input string) (string, error) {
522 inputCmd := SplitCommandArgs(input)[0]
523 args := SplitCommandArgs(input)[1:]
525 cmd := exec.Command(inputCmd, args...)
526 outputBytes := &bytes.Buffer{}
527 cmd.Stdout = outputBytes
528 cmd.Stderr = outputBytes
530 err := cmd.Wait() // wait for command to finish
531 outstring := outputBytes.String()
532 return outstring, err
535 // HandleShellCommand runs the shell command
536 // The openTerm argument specifies whether a terminal should be opened (for viewing output
537 // or interacting with stdin)
538 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
539 inputCmd := SplitCommandArgs(input)[0]
541 // Simply run the command in the background and notify the user when it's done
542 messenger.Message("Running...")
544 output, err := RunShellCommand(input)
545 totalLines := strings.Split(output, "\n")
547 if len(totalLines) < 3 {
549 messenger.Message(inputCmd, " exited without error")
551 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
554 messenger.Message(output)
556 // We have to make sure to redraw
560 // Shut down the screen because we're going to interact directly with the shell
564 args := SplitCommandArgs(input)[1:]
566 // Set up everything for the command
567 var outputBuf bytes.Buffer
568 cmd := exec.Command(inputCmd, args...)
570 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
571 cmd.Stderr = os.Stderr
573 // This is a trap for Ctrl-C so that it doesn't kill micro
574 // Instead we trap Ctrl-C to kill the program we're running
575 c := make(chan os.Signal, 1)
576 signal.Notify(c, os.Interrupt)
586 output := outputBuf.String()
592 // This is just so we don't return right away and let the user press enter to return
596 // Start the screen back up
604 // HandleCommand handles input from the user
605 func HandleCommand(input string) {
606 args := SplitCommandArgs(input)
609 if _, ok := commands[inputCmd]; !ok {
610 messenger.Error("Unknown command ", inputCmd)
612 commands[inputCmd].action(args[1:])