13 "github.com/mitchellh/go-homedir"
18 completions []Completion
21 type StrCommand struct {
23 completions []Completion
26 var commands map[string]Command
28 var commandActions = map[string]func([]string){
42 "ToggleLog": ToggleLog,
46 // InitCommands initializes the default commands
48 commands = make(map[string]Command)
50 defaults := DefaultCommands()
51 parseCommands(defaults)
54 func parseCommands(userCommands map[string]StrCommand) {
55 for k, v := range userCommands {
56 MakeCommand(k, v.action, v.completions...)
60 // MakeCommand is a function to easily create new commands
61 // This can be called by plugins in Lua so that plugins can define their own commands
62 func MakeCommand(name, function string, completions ...Completion) {
63 action := commandActions[function]
64 if _, ok := commandActions[function]; !ok {
65 // If the user seems to be binding a function that doesn't exist
66 // We hope that it's a lua function that exists and bind it to that
67 action = LuaFunctionCommand(function)
70 commands[name] = Command{action, completions}
73 // DefaultCommands returns a map containing micro's default commands
74 func DefaultCommands() map[string]StrCommand {
75 return map[string]StrCommand{
76 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
77 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
78 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
79 "bind": {"Bind", []Completion{NoCompletion}},
80 "run": {"Run", []Completion{NoCompletion}},
81 "quit": {"Quit", []Completion{NoCompletion}},
82 "save": {"Save", []Completion{NoCompletion}},
83 "replace": {"Replace", []Completion{NoCompletion}},
84 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
85 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
86 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
87 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
88 "eval": {"Eval", []Completion{NoCompletion}},
89 "log": {"ToggleLog", []Completion{NoCompletion}},
90 "plugin": {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
94 // InstallPlugin installs the given plugin by exact name match
95 func PluginCmd(args []string) {
99 for _, plugin := range args[1:] {
100 pp := GetAllPluginPackages().Get(plugin)
102 messenger.Error("Unknown plugin \"" + plugin + "\"")
103 } else if !pp.IsInstallable() {
104 messenger.Error("Plugin \"" + plugin + "\" can not be installed.")
110 for _, plugin := range args[1:] {
111 // check if the plugin exists.
112 for _, lp := range loadedPlugins {
114 UninstallPlugin(plugin)
120 UpdatePlugins(args[1:])
122 searchText := strings.Join(args[1:], " ")
123 plugins := SearchPlugin(searchText)
124 messenger.Message(len(plugins), " plugins found")
125 for _, p := range plugins {
126 messenger.AddLog("\n")
127 messenger.AddLog(p.String())
129 if len(plugins) > 0 {
130 if CurView().Type != vtLog {
131 ToggleLog([]string{})
136 messenger.Error("Not enough arguments")
140 func ToggleLog(args []string) {
141 buffer := messenger.getBuffer()
142 if CurView().Type != vtLog {
143 CurView().HSplit(buffer)
144 CurView().Type = vtLog
150 // Help tries to open the given help page in a horizontal split
151 func Help(args []string) {
153 // Open the default help if the user just typed "> help"
154 CurView().openHelp("help")
157 if FindRuntimeFile(RTHelp, helpPage) != nil {
158 CurView().openHelp(helpPage)
160 messenger.Error("Sorry, no help for ", helpPage)
165 // VSplit opens a vertical split with file given in the first argument
166 // If no file is given, it opens an empty buffer in a new split
167 func VSplit(args []string) {
169 CurView().VSplit(NewBuffer([]byte{}, ""))
172 home, _ := homedir.Dir()
173 filename = strings.Replace(filename, "~", home, 1)
174 file, err := ioutil.ReadFile(filename)
178 // File does not exist -- create an empty buffer with that name
179 buf = NewBuffer([]byte{}, filename)
181 buf = NewBuffer(file, filename)
183 CurView().VSplit(buf)
187 // HSplit opens a horizontal split with file given in the first argument
188 // If no file is given, it opens an empty buffer in a new split
189 func HSplit(args []string) {
191 CurView().HSplit(NewBuffer([]byte{}, ""))
194 home, _ := homedir.Dir()
195 filename = strings.Replace(filename, "~", home, 1)
196 file, err := ioutil.ReadFile(filename)
200 // File does not exist -- create an empty buffer with that name
201 buf = NewBuffer([]byte{}, filename)
203 buf = NewBuffer(file, filename)
205 CurView().HSplit(buf)
209 // Eval evaluates a lua expression
210 func Eval(args []string) {
212 err := L.DoString(args[0])
217 messenger.Error("Not enough arguments")
221 // NewTab opens the given file in a new tab
222 func NewTab(args []string) {
224 CurView().AddTab(true)
227 home, _ := homedir.Dir()
228 filename = strings.Replace(filename, "~", home, 1)
229 file, _ := ioutil.ReadFile(filename)
231 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
232 tab.SetNum(len(tabs))
233 tabs = append(tabs, tab)
236 for _, t := range tabs {
237 for _, v := range t.views {
245 // Set sets an option
246 func Set(args []string) {
248 messenger.Error("Not enough arguments")
252 option := strings.TrimSpace(args[0])
253 value := strings.TrimSpace(args[1])
255 SetOptionAndSettings(option, value)
258 // SetLocal sets an option local to the buffer
259 func SetLocal(args []string) {
261 messenger.Error("Not enough arguments")
265 option := strings.TrimSpace(args[0])
266 value := strings.TrimSpace(args[1])
268 err := SetLocalOption(option, value, CurView())
270 messenger.Error(err.Error())
274 // Show shows the value of the given option
275 func Show(args []string) {
277 messenger.Error("Please provide an option to show")
281 option := GetOption(args[0])
284 messenger.Error(args[0], " is not a valid option")
288 messenger.Message(option)
291 // Bind creates a new keybinding
292 func Bind(args []string) {
294 messenger.Error("Not enough arguments")
297 BindKey(args[0], args[1])
300 // Run runs a shell command in the background
301 func Run(args []string) {
302 // Run a shell command in the background (openTerm is false)
303 HandleShellCommand(JoinCommandArgs(args...), false, true)
306 // Quit closes the main view
307 func Quit(args []string) {
308 // Close the main view
312 // Save saves the buffer in the main view
313 func Save(args []string) {
315 // Save the main view
318 CurView().Buf.SaveAs(args[0])
322 // Replace runs search and replace
323 func Replace(args []string) {
325 // We need to find both a search and replace expression
326 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
332 // The user included some flags
336 search := string(args[0])
337 replace := string(args[1])
339 regex, err := regexp.Compile(search)
341 // There was an error with the user's regex
342 messenger.Error(err.Error())
349 if strings.Contains(flags, "c") {
351 // The 'check' flag was used
352 Search(search, view, true)
353 if !view.Cursor.HasSelection() {
357 if view.Buf.Settings["syntax"].(bool) {
358 view.matches = Match(view)
361 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
363 if view.Cursor.HasSelection() {
364 view.Cursor.Loc = view.Cursor.CurSelection[0]
365 view.Cursor.ResetSelection()
371 view.Cursor.DeleteSelection()
372 view.Buf.Insert(view.Cursor.Loc, replace)
373 view.Cursor.ResetSelection()
377 if view.Cursor.HasSelection() {
378 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
380 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
386 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
387 if matches != nil && len(matches) > 0 {
389 prevMatch := matches[0]
390 from := FromCharPos(prevMatch[0], view.Buf)
391 to := from.Move(Count(search), view.Buf)
392 adjust += Count(replace) - Count(search)
393 view.Buf.Replace(from, to, replace)
394 if len(matches) > 1 {
395 for _, match := range matches[1:] {
397 from = from.Move(match[0]-prevMatch[0]+adjust, view.Buf)
398 to := from.Move(Count(search), view.Buf)
399 // TermMessage(match[0], " ", prevMatch[0], " ", adjust, "\n", from, " ", to)
400 view.Buf.Replace(from, to, replace)
402 // adjust += Count(replace) - Count(search)
407 view.Cursor.Relocate()
410 messenger.Message("Replaced ", found, " occurrences of ", search)
411 } else if found == 1 {
412 messenger.Message("Replaced ", found, " occurrence of ", search)
414 messenger.Message("Nothing matched ", search)
418 // RunShellCommand executes a shell command and returns the output/error
419 func RunShellCommand(input string) (string, error) {
420 inputCmd := SplitCommandArgs(input)[0]
421 args := SplitCommandArgs(input)[1:]
423 cmd := exec.Command(inputCmd, args...)
424 outputBytes := &bytes.Buffer{}
425 cmd.Stdout = outputBytes
426 cmd.Stderr = outputBytes
428 err := cmd.Wait() // wait for command to finish
429 outstring := outputBytes.String()
430 return outstring, err
433 // HandleShellCommand runs the shell command
434 // The openTerm argument specifies whether a terminal should be opened (for viewing output
435 // or interacting with stdin)
436 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
437 inputCmd := SplitCommandArgs(input)[0]
439 // Simply run the command in the background and notify the user when it's done
440 messenger.Message("Running...")
442 output, err := RunShellCommand(input)
443 totalLines := strings.Split(output, "\n")
445 if len(totalLines) < 3 {
447 messenger.Message(inputCmd, " exited without error")
449 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
452 messenger.Message(output)
454 // We have to make sure to redraw
458 // Shut down the screen because we're going to interact directly with the shell
462 args := SplitCommandArgs(input)[1:]
464 // Set up everything for the command
465 var outputBuf bytes.Buffer
466 cmd := exec.Command(inputCmd, args...)
468 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
469 cmd.Stderr = os.Stderr
471 // This is a trap for Ctrl-C so that it doesn't kill micro
472 // Instead we trap Ctrl-C to kill the program we're running
473 c := make(chan os.Signal, 1)
474 signal.Notify(c, os.Interrupt)
484 output := outputBuf.String()
490 // This is just so we don't return right away and let the user press enter to return
494 // Start the screen back up
502 // HandleCommand handles input from the user
503 func HandleCommand(input string) {
504 args := SplitCommandArgs(input)
507 if _, ok := commands[inputCmd]; !ok {
508 messenger.Error("Unknown command ", inputCmd)
510 commands[inputCmd].action(args[1:])