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,
52 // InitCommands initializes the default commands
54 commands = make(map[string]Command)
56 defaults := DefaultCommands()
57 parseCommands(defaults)
60 func parseCommands(userCommands map[string]StrCommand) {
61 for k, v := range userCommands {
62 MakeCommand(k, v.action, v.completions...)
66 // MakeCommand is a function to easily create new commands
67 // This can be called by plugins in Lua so that plugins can define their own commands
68 func MakeCommand(name, function string, completions ...Completion) {
69 action := commandActions[function]
70 if _, ok := commandActions[function]; !ok {
71 // If the user seems to be binding a function that doesn't exist
72 // We hope that it's a lua function that exists and bind it to that
73 action = LuaFunctionCommand(function)
76 commands[name] = Command{action, completions}
79 // DefaultCommands returns a map containing micro's default commands
80 func DefaultCommands() map[string]StrCommand {
81 return map[string]StrCommand{
82 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
83 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
84 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
85 "bind": {"Bind", []Completion{NoCompletion}},
86 "run": {"Run", []Completion{NoCompletion}},
87 "quit": {"Quit", []Completion{NoCompletion}},
88 "save": {"Save", []Completion{NoCompletion}},
89 "replace": {"Replace", []Completion{NoCompletion}},
90 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
91 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
92 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
93 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
94 "eval": {"Eval", []Completion{NoCompletion}},
95 "log": {"ToggleLog", []Completion{NoCompletion}},
96 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
97 "reload": {"Reload", []Completion{NoCompletion}},
101 // PluginCmd installs, removes, updates, lists, or searches for given plugins
102 func PluginCmd(args []string) {
106 installedVersions := GetInstalledVersions(false)
107 for _, plugin := range args[1:] {
108 pp := GetAllPluginPackages().Get(plugin)
110 messenger.Error("Unknown plugin \"" + plugin + "\"")
111 } else if err := pp.IsInstallable(); err != nil {
112 messenger.Error("Error installing ", plugin, ": ", err)
114 for _, installed := range installedVersions {
115 if pp.Name == installed.pack.Name {
116 if pp.Versions[0].Version.Compare(installed.Version) == 1 {
117 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
119 messenger.Error(pp.Name, " is already installed")
128 for _, plugin := range args[1:] {
129 // check if the plugin exists.
130 for _, lp := range loadedPlugins {
132 UninstallPlugin(plugin)
133 removed += plugin + " "
138 if !IsSpaces(removed) {
139 messenger.Message("Removed ", removed)
141 messenger.Error("The requested plugins do not exist")
144 UpdatePlugins(args[1:])
146 plugins := GetInstalledVersions(false)
147 messenger.AddLog("----------------")
148 messenger.AddLog("The following plugins are currently installed:\n")
149 for _, p := range plugins {
150 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
152 messenger.AddLog("----------------")
153 if len(plugins) > 0 {
154 if CurView().Type != vtLog {
155 ToggleLog([]string{})
159 plugins := SearchPlugin(args[1:])
160 messenger.Message(len(plugins), " plugins found")
161 for _, p := range plugins {
162 messenger.AddLog("----------------")
163 messenger.AddLog(p.String())
165 messenger.AddLog("----------------")
166 if len(plugins) > 0 {
167 if CurView().Type != vtLog {
168 ToggleLog([]string{})
172 packages := GetAllPluginPackages()
173 messenger.AddLog("Available Plugins:")
174 for _, pkg := range packages {
175 messenger.AddLog(pkg.Name)
177 if CurView().Type != vtLog {
178 ToggleLog([]string{})
182 messenger.Error("Not enough arguments")
186 func ToggleLog(args []string) {
187 buffer := messenger.getBuffer()
188 if CurView().Type != vtLog {
189 CurView().HSplit(buffer)
190 CurView().Type = vtLog
192 buffer.Cursor.Loc = buffer.Start()
194 buffer.Cursor.Loc = buffer.End()
201 func Reload(args []string) {
205 // Help tries to open the given help page in a horizontal split
206 func Help(args []string) {
208 // Open the default help if the user just typed "> help"
209 CurView().openHelp("help")
212 if FindRuntimeFile(RTHelp, helpPage) != nil {
213 CurView().openHelp(helpPage)
215 messenger.Error("Sorry, no help for ", helpPage)
220 // VSplit opens a vertical split with file given in the first argument
221 // If no file is given, it opens an empty buffer in a new split
222 func VSplit(args []string) {
224 CurView().VSplit(NewBuffer([]byte{}, ""))
227 home, _ := homedir.Dir()
228 filename = strings.Replace(filename, "~", home, 1)
229 file, err := ioutil.ReadFile(filename)
233 // File does not exist -- create an empty buffer with that name
234 buf = NewBuffer([]byte{}, filename)
236 buf = NewBuffer(file, filename)
238 CurView().VSplit(buf)
242 // HSplit opens a horizontal split with file given in the first argument
243 // If no file is given, it opens an empty buffer in a new split
244 func HSplit(args []string) {
246 CurView().HSplit(NewBuffer([]byte{}, ""))
249 home, _ := homedir.Dir()
250 filename = strings.Replace(filename, "~", home, 1)
251 file, err := ioutil.ReadFile(filename)
255 // File does not exist -- create an empty buffer with that name
256 buf = NewBuffer([]byte{}, filename)
258 buf = NewBuffer(file, filename)
260 CurView().HSplit(buf)
264 // Eval evaluates a lua expression
265 func Eval(args []string) {
267 err := L.DoString(args[0])
272 messenger.Error("Not enough arguments")
276 // NewTab opens the given file in a new tab
277 func NewTab(args []string) {
279 CurView().AddTab(true)
282 home, _ := homedir.Dir()
283 filename = strings.Replace(filename, "~", home, 1)
284 file, _ := ioutil.ReadFile(filename)
286 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
287 tab.SetNum(len(tabs))
288 tabs = append(tabs, tab)
291 for _, t := range tabs {
292 for _, v := range t.views {
300 // Set sets an option
301 func Set(args []string) {
303 messenger.Error("Not enough arguments")
307 option := strings.TrimSpace(args[0])
308 value := strings.TrimSpace(args[1])
310 SetOptionAndSettings(option, value)
313 // SetLocal sets an option local to the buffer
314 func SetLocal(args []string) {
316 messenger.Error("Not enough arguments")
320 option := strings.TrimSpace(args[0])
321 value := strings.TrimSpace(args[1])
323 err := SetLocalOption(option, value, CurView())
325 messenger.Error(err.Error())
329 // Show shows the value of the given option
330 func Show(args []string) {
332 messenger.Error("Please provide an option to show")
336 option := GetOption(args[0])
339 messenger.Error(args[0], " is not a valid option")
343 messenger.Message(option)
346 // Bind creates a new keybinding
347 func Bind(args []string) {
349 messenger.Error("Not enough arguments")
352 BindKey(args[0], args[1])
355 // Run runs a shell command in the background
356 func Run(args []string) {
357 // Run a shell command in the background (openTerm is false)
358 HandleShellCommand(JoinCommandArgs(args...), false, true)
361 // Quit closes the main view
362 func Quit(args []string) {
363 // Close the main view
367 // Save saves the buffer in the main view
368 func Save(args []string) {
370 // Save the main view
373 CurView().Buf.SaveAs(args[0])
377 // Replace runs search and replace
378 func Replace(args []string) {
380 // We need to find both a search and replace expression
381 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
387 // The user included some flags
391 search := string(args[0])
392 replace := string(args[1])
394 regex, err := regexp.Compile("(?m)" + search)
396 // There was an error with the user's regex
397 messenger.Error(err.Error())
404 if strings.Contains(flags, "c") {
406 // The 'check' flag was used
407 Search(search, view, true)
408 if !view.Cursor.HasSelection() {
412 if view.Buf.Settings["syntax"].(bool) {
413 view.matches = Match(view)
416 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
418 if view.Cursor.HasSelection() {
419 view.Cursor.Loc = view.Cursor.CurSelection[0]
420 view.Cursor.ResetSelection()
426 view.Cursor.DeleteSelection()
427 view.Buf.Insert(view.Cursor.Loc, replace)
428 view.Cursor.ResetSelection()
432 if view.Cursor.HasSelection() {
433 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
435 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
441 bufStr := view.Buf.String()
442 matches := regex.FindAllStringIndex(bufStr, -1)
443 if matches != nil && len(matches) > 0 {
444 prevMatchCount := runePos(matches[0][0], bufStr)
445 searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
446 from := FromCharPos(matches[0][0], view.Buf)
447 to := from.Move(searchCount, view.Buf)
448 adjust := Count(replace) - searchCount
449 view.Buf.Replace(from, to, replace)
450 if len(matches) > 1 {
451 for _, match := range matches[1:] {
453 matchCount := runePos(match[0], bufStr)
454 searchCount = runePos(match[1], bufStr) - matchCount
455 from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
456 to = from.Move(searchCount, view.Buf)
457 view.Buf.Replace(from, to, replace)
458 prevMatchCount = matchCount
459 adjust = Count(replace) - searchCount
464 view.Cursor.Relocate()
467 messenger.Message("Replaced ", found, " occurrences of ", search)
468 } else if found == 1 {
469 messenger.Message("Replaced ", found, " occurrence of ", search)
471 messenger.Message("Nothing matched ", search)
475 // RunShellCommand executes a shell command and returns the output/error
476 func RunShellCommand(input string) (string, error) {
477 inputCmd := SplitCommandArgs(input)[0]
478 args := SplitCommandArgs(input)[1:]
480 cmd := exec.Command(inputCmd, args...)
481 outputBytes := &bytes.Buffer{}
482 cmd.Stdout = outputBytes
483 cmd.Stderr = outputBytes
485 err := cmd.Wait() // wait for command to finish
486 outstring := outputBytes.String()
487 return outstring, err
490 // HandleShellCommand runs the shell command
491 // The openTerm argument specifies whether a terminal should be opened (for viewing output
492 // or interacting with stdin)
493 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
494 inputCmd := SplitCommandArgs(input)[0]
496 // Simply run the command in the background and notify the user when it's done
497 messenger.Message("Running...")
499 output, err := RunShellCommand(input)
500 totalLines := strings.Split(output, "\n")
502 if len(totalLines) < 3 {
504 messenger.Message(inputCmd, " exited without error")
506 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
509 messenger.Message(output)
511 // We have to make sure to redraw
515 // Shut down the screen because we're going to interact directly with the shell
519 args := SplitCommandArgs(input)[1:]
521 // Set up everything for the command
522 var outputBuf bytes.Buffer
523 cmd := exec.Command(inputCmd, args...)
525 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
526 cmd.Stderr = os.Stderr
528 // This is a trap for Ctrl-C so that it doesn't kill micro
529 // Instead we trap Ctrl-C to kill the program we're running
530 c := make(chan os.Signal, 1)
531 signal.Notify(c, os.Interrupt)
541 output := outputBuf.String()
547 // This is just so we don't return right away and let the user press enter to return
551 // Start the screen back up
559 // HandleCommand handles input from the user
560 func HandleCommand(input string) {
561 args := SplitCommandArgs(input)
564 if _, ok := commands[inputCmd]; !ok {
565 messenger.Error("Unknown command ", inputCmd)
567 commands[inputCmd].action(args[1:])