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){
43 "ToggleLog": ToggleLog,
47 // InitCommands initializes the default commands
49 commands = make(map[string]Command)
51 defaults := DefaultCommands()
52 parseCommands(defaults)
55 func parseCommands(userCommands map[string]StrCommand) {
56 for k, v := range userCommands {
57 MakeCommand(k, v.action, v.completions...)
61 // MakeCommand is a function to easily create new commands
62 // This can be called by plugins in Lua so that plugins can define their own commands
63 func MakeCommand(name, function string, completions ...Completion) {
64 action := commandActions[function]
65 if _, ok := commandActions[function]; !ok {
66 // If the user seems to be binding a function that doesn't exist
67 // We hope that it's a lua function that exists and bind it to that
68 action = LuaFunctionCommand(function)
71 commands[name] = Command{action, completions}
74 // DefaultCommands returns a map containing micro's default commands
75 func DefaultCommands() map[string]StrCommand {
76 return map[string]StrCommand{
77 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
78 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
79 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
80 "bind": {"Bind", []Completion{NoCompletion}},
81 "run": {"Run", []Completion{NoCompletion}},
82 "quit": {"Quit", []Completion{NoCompletion}},
83 "save": {"Save", []Completion{NoCompletion}},
84 "replace": {"Replace", []Completion{NoCompletion}},
85 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
86 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
87 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
88 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
89 "eval": {"Eval", []Completion{NoCompletion}},
90 "log": {"ToggleLog", []Completion{NoCompletion}},
91 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
95 // PluginCmd installs, removes, updates, lists, or searches for given plugins
96 func PluginCmd(args []string) {
100 installedVersions := GetInstalledVersions(false)
101 for _, plugin := range args[1:] {
102 pp := GetAllPluginPackages().Get(plugin)
104 messenger.Error("Unknown plugin \"" + plugin + "\"")
105 } else if err := pp.IsInstallable(); err != nil {
106 messenger.Error("Error installing ", plugin, ": ", err)
108 for _, installed := range installedVersions {
109 if pp.Name == installed.pack.Name {
110 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
111 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
113 messenger.Error(pp.Name, " is already installed")
122 for _, plugin := range args[1:] {
123 // check if the plugin exists.
124 for _, lp := range loadedPlugins {
126 UninstallPlugin(plugin)
127 removed += plugin + " "
132 if !IsSpaces(removed) {
133 messenger.Message("Removed ", removed)
135 messenger.Error("The requested plugins do not exist")
138 UpdatePlugins(args[1:])
140 plugins := GetInstalledVersions(false)
141 messenger.AddLog("----------------")
142 messenger.AddLog("The following plugins are currently installed:\n")
143 for _, p := range plugins {
144 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
146 messenger.AddLog("----------------")
147 if len(plugins) > 0 {
148 if CurView().Type != vtLog {
149 ToggleLog([]string{})
153 plugins := SearchPlugin(args[1:])
154 messenger.Message(len(plugins), " plugins found")
155 for _, p := range plugins {
156 messenger.AddLog("----------------")
157 messenger.AddLog(p.String())
159 messenger.AddLog("----------------")
160 if len(plugins) > 0 {
161 if CurView().Type != vtLog {
162 ToggleLog([]string{})
167 messenger.Error("Not enough arguments")
171 func ToggleLog(args []string) {
172 buffer := messenger.getBuffer()
173 if CurView().Type != vtLog {
174 CurView().HSplit(buffer)
175 CurView().Type = vtLog
181 // Help tries to open the given help page in a horizontal split
182 func Help(args []string) {
184 // Open the default help if the user just typed "> help"
185 CurView().openHelp("help")
188 if FindRuntimeFile(RTHelp, helpPage) != nil {
189 CurView().openHelp(helpPage)
191 messenger.Error("Sorry, no help for ", helpPage)
196 // VSplit opens a vertical split with file given in the first argument
197 // If no file is given, it opens an empty buffer in a new split
198 func VSplit(args []string) {
200 CurView().VSplit(NewBuffer([]byte{}, ""))
203 home, _ := homedir.Dir()
204 filename = strings.Replace(filename, "~", home, 1)
205 file, err := ioutil.ReadFile(filename)
209 // File does not exist -- create an empty buffer with that name
210 buf = NewBuffer([]byte{}, filename)
212 buf = NewBuffer(file, filename)
214 CurView().VSplit(buf)
218 // HSplit opens a horizontal split with file given in the first argument
219 // If no file is given, it opens an empty buffer in a new split
220 func HSplit(args []string) {
222 CurView().HSplit(NewBuffer([]byte{}, ""))
225 home, _ := homedir.Dir()
226 filename = strings.Replace(filename, "~", home, 1)
227 file, err := ioutil.ReadFile(filename)
231 // File does not exist -- create an empty buffer with that name
232 buf = NewBuffer([]byte{}, filename)
234 buf = NewBuffer(file, filename)
236 CurView().HSplit(buf)
240 // Eval evaluates a lua expression
241 func Eval(args []string) {
243 err := L.DoString(args[0])
248 messenger.Error("Not enough arguments")
252 // NewTab opens the given file in a new tab
253 func NewTab(args []string) {
255 CurView().AddTab(true)
258 home, _ := homedir.Dir()
259 filename = strings.Replace(filename, "~", home, 1)
260 file, _ := ioutil.ReadFile(filename)
262 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
263 tab.SetNum(len(tabs))
264 tabs = append(tabs, tab)
267 for _, t := range tabs {
268 for _, v := range t.views {
276 // Set sets an option
277 func Set(args []string) {
279 messenger.Error("Not enough arguments")
283 option := strings.TrimSpace(args[0])
284 value := strings.TrimSpace(args[1])
286 SetOptionAndSettings(option, value)
289 // SetLocal sets an option local to the buffer
290 func SetLocal(args []string) {
292 messenger.Error("Not enough arguments")
296 option := strings.TrimSpace(args[0])
297 value := strings.TrimSpace(args[1])
299 err := SetLocalOption(option, value, CurView())
301 messenger.Error(err.Error())
305 // Show shows the value of the given option
306 func Show(args []string) {
308 messenger.Error("Please provide an option to show")
312 option := GetOption(args[0])
315 messenger.Error(args[0], " is not a valid option")
319 messenger.Message(option)
322 // Bind creates a new keybinding
323 func Bind(args []string) {
325 messenger.Error("Not enough arguments")
328 BindKey(args[0], args[1])
331 // Run runs a shell command in the background
332 func Run(args []string) {
333 // Run a shell command in the background (openTerm is false)
334 HandleShellCommand(JoinCommandArgs(args...), false, true)
337 // Quit closes the main view
338 func Quit(args []string) {
339 // Close the main view
343 // Save saves the buffer in the main view
344 func Save(args []string) {
346 // Save the main view
349 CurView().Buf.SaveAs(args[0])
353 // Replace runs search and replace
354 func Replace(args []string) {
356 // We need to find both a search and replace expression
357 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
363 // The user included some flags
367 search := string(args[0])
368 replace := string(args[1])
370 regex, err := regexp.Compile(search)
372 // There was an error with the user's regex
373 messenger.Error(err.Error())
380 if strings.Contains(flags, "c") {
382 // The 'check' flag was used
383 Search(search, view, true)
384 if !view.Cursor.HasSelection() {
388 if view.Buf.Settings["syntax"].(bool) {
389 view.matches = Match(view)
392 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
394 if view.Cursor.HasSelection() {
395 view.Cursor.Loc = view.Cursor.CurSelection[0]
396 view.Cursor.ResetSelection()
402 view.Cursor.DeleteSelection()
403 view.Buf.Insert(view.Cursor.Loc, replace)
404 view.Cursor.ResetSelection()
408 if view.Cursor.HasSelection() {
409 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
411 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
417 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
418 if matches != nil && len(matches) > 0 {
420 prevMatch := matches[0]
421 from := FromCharPos(prevMatch[0], view.Buf)
422 to := from.Move(Count(search), view.Buf)
423 adjust += Count(replace) - Count(search)
424 view.Buf.Replace(from, to, replace)
425 if len(matches) > 1 {
426 for _, match := range matches[1:] {
428 from = from.Move(match[0]-prevMatch[0]+adjust, view.Buf)
429 to := from.Move(Count(search), view.Buf)
430 // TermMessage(match[0], " ", prevMatch[0], " ", adjust, "\n", from, " ", to)
431 view.Buf.Replace(from, to, replace)
433 // adjust += Count(replace) - Count(search)
438 view.Cursor.Relocate()
441 messenger.Message("Replaced ", found, " occurrences of ", search)
442 } else if found == 1 {
443 messenger.Message("Replaced ", found, " occurrence of ", search)
445 messenger.Message("Nothing matched ", search)
449 // RunShellCommand executes a shell command and returns the output/error
450 func RunShellCommand(input string) (string, error) {
451 inputCmd := SplitCommandArgs(input)[0]
452 args := SplitCommandArgs(input)[1:]
454 cmd := exec.Command(inputCmd, args...)
455 outputBytes := &bytes.Buffer{}
456 cmd.Stdout = outputBytes
457 cmd.Stderr = outputBytes
459 err := cmd.Wait() // wait for command to finish
460 outstring := outputBytes.String()
461 return outstring, err
464 // HandleShellCommand runs the shell command
465 // The openTerm argument specifies whether a terminal should be opened (for viewing output
466 // or interacting with stdin)
467 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
468 inputCmd := SplitCommandArgs(input)[0]
470 // Simply run the command in the background and notify the user when it's done
471 messenger.Message("Running...")
473 output, err := RunShellCommand(input)
474 totalLines := strings.Split(output, "\n")
476 if len(totalLines) < 3 {
478 messenger.Message(inputCmd, " exited without error")
480 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
483 messenger.Message(output)
485 // We have to make sure to redraw
489 // Shut down the screen because we're going to interact directly with the shell
493 args := SplitCommandArgs(input)[1:]
495 // Set up everything for the command
496 var outputBuf bytes.Buffer
497 cmd := exec.Command(inputCmd, args...)
499 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
500 cmd.Stderr = os.Stderr
502 // This is a trap for Ctrl-C so that it doesn't kill micro
503 // Instead we trap Ctrl-C to kill the program we're running
504 c := make(chan os.Signal, 1)
505 signal.Notify(c, os.Interrupt)
515 output := outputBuf.String()
521 // This is just so we don't return right away and let the user press enter to return
525 // Start the screen back up
533 // HandleCommand handles input from the user
534 func HandleCommand(input string) {
535 args := SplitCommandArgs(input)
538 if _, ok := commands[inputCmd]; !ok {
539 messenger.Error("Unknown command ", inputCmd)
541 commands[inputCmd].action(args[1:])