15 "github.com/mitchellh/go-homedir"
20 completions []Completion
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){
47 "ToggleLog": ToggleLog,
53 "TabSwitch": TabSwitch,
57 // InitCommands initializes the default commands
59 commands = make(map[string]Command)
61 defaults := DefaultCommands()
62 parseCommands(defaults)
65 func parseCommands(userCommands map[string]StrCommand) {
66 for k, v := range userCommands {
67 MakeCommand(k, v.action, v.completions...)
71 // MakeCommand is a function to easily create new commands
72 // This can be called by plugins in Lua so that plugins can define their own commands
73 func MakeCommand(name, function string, completions ...Completion) {
74 action := commandActions[function]
75 if _, ok := commandActions[function]; !ok {
76 // If the user seems to be binding a function that doesn't exist
77 // We hope that it's a lua function that exists and bind it to that
78 action = LuaFunctionCommand(function)
81 commands[name] = Command{action, completions}
84 // DefaultCommands returns a map containing micro's default commands
85 func DefaultCommands() map[string]StrCommand {
86 return map[string]StrCommand{
87 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
88 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
89 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
90 "bind": {"Bind", []Completion{NoCompletion}},
91 "run": {"Run", []Completion{NoCompletion}},
92 "quit": {"Quit", []Completion{NoCompletion}},
93 "save": {"Save", []Completion{NoCompletion}},
94 "replace": {"Replace", []Completion{NoCompletion}},
95 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
96 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
97 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
98 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
99 "eval": {"Eval", []Completion{NoCompletion}},
100 "log": {"ToggleLog", []Completion{NoCompletion}},
101 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
102 "reload": {"Reload", []Completion{NoCompletion}},
103 "cd": {"Cd", []Completion{FileCompletion}},
104 "pwd": {"Pwd", []Completion{NoCompletion}},
105 "open": {"Open", []Completion{FileCompletion}},
106 "tabswitch": {"TabSwitch", []Completion{NoCompletion}},
110 // PluginCmd installs, removes, updates, lists, or searches for given plugins
111 func PluginCmd(args []string) {
115 installedVersions := GetInstalledVersions(false)
116 for _, plugin := range args[1:] {
117 pp := GetAllPluginPackages().Get(plugin)
119 messenger.Error("Unknown plugin \"" + plugin + "\"")
120 } else if err := pp.IsInstallable(); err != nil {
121 messenger.Error("Error installing ", plugin, ": ", err)
123 for _, installed := range installedVersions {
124 if pp.Name == installed.pack.Name {
125 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
126 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
128 messenger.Error(pp.Name, " is already installed")
137 for _, plugin := range args[1:] {
138 // check if the plugin exists.
139 if _, ok := loadedPlugins[plugin]; ok {
140 UninstallPlugin(plugin)
141 removed += plugin + " "
145 if !IsSpaces(removed) {
146 messenger.Message("Removed ", removed)
148 messenger.Error("The requested plugins do not exist")
151 UpdatePlugins(args[1:])
153 plugins := GetInstalledVersions(false)
154 messenger.AddLog("----------------")
155 messenger.AddLog("The following plugins are currently installed:\n")
156 for _, p := range plugins {
157 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
159 messenger.AddLog("----------------")
160 if len(plugins) > 0 {
161 if CurView().Type != vtLog {
162 ToggleLog([]string{})
166 plugins := SearchPlugin(args[1:])
167 messenger.Message(len(plugins), " plugins found")
168 for _, p := range plugins {
169 messenger.AddLog("----------------")
170 messenger.AddLog(p.String())
172 messenger.AddLog("----------------")
173 if len(plugins) > 0 {
174 if CurView().Type != vtLog {
175 ToggleLog([]string{})
179 packages := GetAllPluginPackages()
180 messenger.AddLog("Available Plugins:")
181 for _, pkg := range packages {
182 messenger.AddLog(pkg.Name)
184 if CurView().Type != vtLog {
185 ToggleLog([]string{})
189 messenger.Error("Not enough arguments")
193 func TabSwitch(args []string) {
195 num, err := strconv.Atoi(args[0])
197 // Check for tab with this name
200 for _, t := range tabs {
201 v := t.views[t.CurView]
202 if v.Buf.GetName() == args[0] {
208 messenger.Error("Could not find tab: ", err)
212 if num >= 0 && num < len(tabs) {
215 messenger.Error("Invalid tab index")
221 func Cd(args []string) {
223 home, _ := homedir.Dir()
224 path := strings.Replace(args[0], "~", home, 1)
226 for _, tab := range tabs {
227 for _, view := range tab.views {
229 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
230 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
231 view.Buf.Path = view.Buf.AbsPath
238 func Pwd(args []string) {
239 wd, err := os.Getwd()
241 messenger.Message(err.Error())
243 messenger.Message(wd)
247 func Open(args []string) {
250 // the filename might or might not be quoted, so unquote first then join the strings.
251 filename = strings.Join(SplitCommandArgs(filename), " ")
253 CurView().Open(filename)
255 messenger.Error("No filename")
259 func ToggleLog(args []string) {
260 buffer := messenger.getBuffer()
261 if CurView().Type != vtLog {
262 CurView().HSplit(buffer)
263 CurView().Type = vtLog
265 buffer.Cursor.Loc = buffer.Start()
267 buffer.Cursor.Loc = buffer.End()
274 func Reload(args []string) {
278 // Help tries to open the given help page in a horizontal split
279 func Help(args []string) {
281 // Open the default help if the user just typed "> help"
282 CurView().openHelp("help")
285 if FindRuntimeFile(RTHelp, helpPage) != nil {
286 CurView().openHelp(helpPage)
288 messenger.Error("Sorry, no help for ", helpPage)
293 // VSplit opens a vertical split with file given in the first argument
294 // If no file is given, it opens an empty buffer in a new split
295 func VSplit(args []string) {
297 CurView().VSplit(NewBuffer(strings.NewReader(""), ""))
300 home, _ := homedir.Dir()
301 filename = strings.Replace(filename, "~", home, 1)
302 file, err := os.Open(filename)
307 // File does not exist -- create an empty buffer with that name
308 buf = NewBuffer(strings.NewReader(""), filename)
310 buf = NewBuffer(file, filename)
312 CurView().VSplit(buf)
316 // HSplit opens a horizontal split with file given in the first argument
317 // If no file is given, it opens an empty buffer in a new split
318 func HSplit(args []string) {
320 CurView().HSplit(NewBuffer(strings.NewReader(""), ""))
323 home, _ := homedir.Dir()
324 filename = strings.Replace(filename, "~", home, 1)
325 file, err := os.Open(filename)
330 // File does not exist -- create an empty buffer with that name
331 buf = NewBuffer(strings.NewReader(""), filename)
333 buf = NewBuffer(file, filename)
335 CurView().HSplit(buf)
339 // Eval evaluates a lua expression
340 func Eval(args []string) {
342 err := L.DoString(args[0])
347 messenger.Error("Not enough arguments")
351 // NewTab opens the given file in a new tab
352 func NewTab(args []string) {
354 CurView().AddTab(true)
357 home, _ := homedir.Dir()
358 filename = strings.Replace(filename, "~", home, 1)
359 file, _ := os.Open(filename)
362 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
363 tab.SetNum(len(tabs))
364 tabs = append(tabs, tab)
365 curTab = len(tabs) - 1
367 for _, t := range tabs {
368 for _, v := range t.views {
376 // Set sets an option
377 func Set(args []string) {
379 messenger.Error("Not enough arguments")
386 SetOptionAndSettings(option, value)
389 // SetLocal sets an option local to the buffer
390 func SetLocal(args []string) {
392 messenger.Error("Not enough arguments")
399 err := SetLocalOption(option, value, CurView())
401 messenger.Error(err.Error())
405 // Show shows the value of the given option
406 func Show(args []string) {
408 messenger.Error("Please provide an option to show")
412 option := GetOption(args[0])
415 messenger.Error(args[0], " is not a valid option")
419 messenger.Message(option)
422 // Bind creates a new keybinding
423 func Bind(args []string) {
425 messenger.Error("Not enough arguments")
428 BindKey(args[0], args[1])
431 // Run runs a shell command in the background
432 func Run(args []string) {
433 // Run a shell command in the background (openTerm is false)
434 HandleShellCommand(JoinCommandArgs(args...), false, true)
437 // Quit closes the main view
438 func Quit(args []string) {
439 // Close the main view
443 // Save saves the buffer in the main view
444 func Save(args []string) {
446 // Save the main view
449 CurView().Buf.SaveAs(args[0])
453 // Replace runs search and replace
454 func Replace(args []string) {
456 // We need to find both a search and replace expression
457 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
463 // The user included some flags
467 search := string(args[0])
468 replace := string(args[1])
470 regex, err := regexp.Compile("(?m)" + search)
472 // There was an error with the user's regex
473 messenger.Error(err.Error())
480 if strings.Contains(flags, "c") {
482 // The 'check' flag was used
483 Search(search, view, true)
484 if !view.Cursor.HasSelection() {
488 if view.Buf.Settings["syntax"].(bool) {
489 view.matches = Match(view)
492 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
494 if view.Cursor.HasSelection() {
495 view.Cursor.Loc = view.Cursor.CurSelection[0]
496 view.Cursor.ResetSelection()
502 view.Cursor.DeleteSelection()
503 view.Buf.Insert(view.Cursor.Loc, replace)
504 view.Cursor.ResetSelection()
508 if view.Cursor.HasSelection() {
509 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
511 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
517 bufStr := view.Buf.String()
518 matches := regex.FindAllStringIndex(bufStr, -1)
519 if matches != nil && len(matches) > 0 {
520 prevMatchCount := runePos(matches[0][0], bufStr)
521 searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
522 from := FromCharPos(matches[0][0], view.Buf)
523 to := from.Move(searchCount, view.Buf)
524 adjust := Count(replace) - searchCount
525 view.Buf.Replace(from, to, replace)
527 if len(matches) > 1 {
528 for _, match := range matches[1:] {
530 matchCount := runePos(match[0], bufStr)
531 searchCount = runePos(match[1], bufStr) - matchCount
532 from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
533 to = from.Move(searchCount, view.Buf)
534 view.Buf.Replace(from, to, replace)
535 prevMatchCount = matchCount
536 adjust = Count(replace) - searchCount
541 view.Cursor.Relocate()
544 messenger.Message("Replaced ", found, " occurrences of ", search)
545 } else if found == 1 {
546 messenger.Message("Replaced ", found, " occurrence of ", search)
548 messenger.Message("Nothing matched ", search)
552 // RunShellCommand executes a shell command and returns the output/error
553 func RunShellCommand(input string) (string, error) {
554 inputCmd := SplitCommandArgs(input)[0]
555 args := SplitCommandArgs(input)[1:]
557 cmd := exec.Command(inputCmd, args...)
558 outputBytes := &bytes.Buffer{}
559 cmd.Stdout = outputBytes
560 cmd.Stderr = outputBytes
562 err := cmd.Wait() // wait for command to finish
563 outstring := outputBytes.String()
564 return outstring, err
567 // HandleShellCommand runs the shell command
568 // The openTerm argument specifies whether a terminal should be opened (for viewing output
569 // or interacting with stdin)
570 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
571 inputCmd := SplitCommandArgs(input)[0]
573 // Simply run the command in the background and notify the user when it's done
574 messenger.Message("Running...")
576 output, err := RunShellCommand(input)
577 totalLines := strings.Split(output, "\n")
579 if len(totalLines) < 3 {
581 messenger.Message(inputCmd, " exited without error")
583 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
586 messenger.Message(output)
588 // We have to make sure to redraw
592 // Shut down the screen because we're going to interact directly with the shell
596 args := SplitCommandArgs(input)[1:]
598 // Set up everything for the command
599 var outputBuf bytes.Buffer
600 cmd := exec.Command(inputCmd, args...)
602 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
603 cmd.Stderr = os.Stderr
605 // This is a trap for Ctrl-C so that it doesn't kill micro
606 // Instead we trap Ctrl-C to kill the program we're running
607 c := make(chan os.Signal, 1)
608 signal.Notify(c, os.Interrupt)
618 output := outputBuf.String()
624 // This is just so we don't return right away and let the user press enter to return
628 // Start the screen back up
636 // HandleCommand handles input from the user
637 func HandleCommand(input string) {
638 args := SplitCommandArgs(input)
641 if _, ok := commands[inputCmd]; !ok {
642 messenger.Error("Unknown command ", inputCmd)
644 commands[inputCmd].action(args[1:])