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{NoCompletion}},
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)
123 messenger.Error("Not enough arguments")
127 func ToggleLog(args []string) {
128 buffer := messenger.getBuffer()
129 if CurView().Type != vtLog {
130 CurView().HSplit(buffer)
131 CurView().Type = vtLog
137 // Help tries to open the given help page in a horizontal split
138 func Help(args []string) {
140 // Open the default help if the user just typed "> help"
141 CurView().openHelp("help")
144 if FindRuntimeFile(RTHelp, helpPage) != nil {
145 CurView().openHelp(helpPage)
147 messenger.Error("Sorry, no help for ", helpPage)
152 // VSplit opens a vertical split with file given in the first argument
153 // If no file is given, it opens an empty buffer in a new split
154 func VSplit(args []string) {
156 CurView().VSplit(NewBuffer([]byte{}, ""))
159 home, _ := homedir.Dir()
160 filename = strings.Replace(filename, "~", home, 1)
161 file, err := ioutil.ReadFile(filename)
165 // File does not exist -- create an empty buffer with that name
166 buf = NewBuffer([]byte{}, filename)
168 buf = NewBuffer(file, filename)
170 CurView().VSplit(buf)
174 // HSplit opens a horizontal split with file given in the first argument
175 // If no file is given, it opens an empty buffer in a new split
176 func HSplit(args []string) {
178 CurView().HSplit(NewBuffer([]byte{}, ""))
181 home, _ := homedir.Dir()
182 filename = strings.Replace(filename, "~", home, 1)
183 file, err := ioutil.ReadFile(filename)
187 // File does not exist -- create an empty buffer with that name
188 buf = NewBuffer([]byte{}, filename)
190 buf = NewBuffer(file, filename)
192 CurView().HSplit(buf)
196 // Eval evaluates a lua expression
197 func Eval(args []string) {
199 err := L.DoString(args[0])
204 messenger.Error("Not enough arguments")
208 // NewTab opens the given file in a new tab
209 func NewTab(args []string) {
211 CurView().AddTab(true)
214 home, _ := homedir.Dir()
215 filename = strings.Replace(filename, "~", home, 1)
216 file, _ := ioutil.ReadFile(filename)
218 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
219 tab.SetNum(len(tabs))
220 tabs = append(tabs, tab)
223 for _, t := range tabs {
224 for _, v := range t.views {
232 // Set sets an option
233 func Set(args []string) {
235 messenger.Error("Not enough arguments")
239 option := strings.TrimSpace(args[0])
240 value := strings.TrimSpace(args[1])
242 SetOptionAndSettings(option, value)
245 // SetLocal sets an option local to the buffer
246 func SetLocal(args []string) {
248 messenger.Error("Not enough arguments")
252 option := strings.TrimSpace(args[0])
253 value := strings.TrimSpace(args[1])
255 err := SetLocalOption(option, value, CurView())
257 messenger.Error(err.Error())
261 // Show shows the value of the given option
262 func Show(args []string) {
264 messenger.Error("Please provide an option to show")
268 option := GetOption(args[0])
271 messenger.Error(args[0], " is not a valid option")
275 messenger.Message(option)
278 // Bind creates a new keybinding
279 func Bind(args []string) {
281 messenger.Error("Not enough arguments")
284 BindKey(args[0], args[1])
287 // Run runs a shell command in the background
288 func Run(args []string) {
289 // Run a shell command in the background (openTerm is false)
290 HandleShellCommand(JoinCommandArgs(args...), false, true)
293 // Quit closes the main view
294 func Quit(args []string) {
295 // Close the main view
299 // Save saves the buffer in the main view
300 func Save(args []string) {
302 // Save the main view
305 CurView().Buf.SaveAs(args[0])
309 // Replace runs search and replace
310 func Replace(args []string) {
312 // We need to find both a search and replace expression
313 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
319 // The user included some flags
323 search := string(args[0])
324 replace := string(args[1])
326 regex, err := regexp.Compile(search)
328 // There was an error with the user's regex
329 messenger.Error(err.Error())
336 if strings.Contains(flags, "c") {
338 // The 'check' flag was used
339 Search(search, view, true)
340 if !view.Cursor.HasSelection() {
344 if view.Buf.Settings["syntax"].(bool) {
345 view.matches = Match(view)
348 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
350 if view.Cursor.HasSelection() {
351 view.Cursor.Loc = view.Cursor.CurSelection[0]
352 view.Cursor.ResetSelection()
358 view.Cursor.DeleteSelection()
359 view.Buf.Insert(view.Cursor.Loc, replace)
360 view.Cursor.ResetSelection()
364 if view.Cursor.HasSelection() {
365 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
367 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
373 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
374 if matches != nil && len(matches) > 0 {
376 prevMatch := matches[0]
377 from := FromCharPos(prevMatch[0], view.Buf)
378 to := from.Move(Count(search), view.Buf)
379 adjust += Count(replace) - Count(search)
380 view.Buf.Replace(from, to, replace)
381 if len(matches) > 1 {
382 for _, match := range matches[1:] {
384 from = from.Move(match[0]-prevMatch[0]+adjust, view.Buf)
385 to := from.Move(Count(search), view.Buf)
386 // TermMessage(match[0], " ", prevMatch[0], " ", adjust, "\n", from, " ", to)
387 view.Buf.Replace(from, to, replace)
389 // adjust += Count(replace) - Count(search)
394 view.Cursor.Relocate()
397 messenger.Message("Replaced ", found, " occurrences of ", search)
398 } else if found == 1 {
399 messenger.Message("Replaced ", found, " occurrence of ", search)
401 messenger.Message("Nothing matched ", search)
405 // RunShellCommand executes a shell command and returns the output/error
406 func RunShellCommand(input string) (string, error) {
407 inputCmd := SplitCommandArgs(input)[0]
408 args := SplitCommandArgs(input)[1:]
410 cmd := exec.Command(inputCmd, args...)
411 outputBytes := &bytes.Buffer{}
412 cmd.Stdout = outputBytes
413 cmd.Stderr = outputBytes
415 err := cmd.Wait() // wait for command to finish
416 outstring := outputBytes.String()
417 return outstring, err
420 // HandleShellCommand runs the shell command
421 // The openTerm argument specifies whether a terminal should be opened (for viewing output
422 // or interacting with stdin)
423 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
424 inputCmd := SplitCommandArgs(input)[0]
426 // Simply run the command in the background and notify the user when it's done
427 messenger.Message("Running...")
429 output, err := RunShellCommand(input)
430 totalLines := strings.Split(output, "\n")
432 if len(totalLines) < 3 {
434 messenger.Message(inputCmd, " exited without error")
436 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
439 messenger.Message(output)
441 // We have to make sure to redraw
445 // Shut down the screen because we're going to interact directly with the shell
449 args := SplitCommandArgs(input)[1:]
451 // Set up everything for the command
452 var outputBuf bytes.Buffer
453 cmd := exec.Command(inputCmd, args...)
455 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
456 cmd.Stderr = os.Stderr
458 // This is a trap for Ctrl-C so that it doesn't kill micro
459 // Instead we trap Ctrl-C to kill the program we're running
460 c := make(chan os.Signal, 1)
461 signal.Notify(c, os.Interrupt)
471 output := outputBuf.String()
477 // This is just so we don't return right away and let the user press enter to return
481 // Start the screen back up
489 // HandleCommand handles input from the user
490 func HandleCommand(input string) {
491 args := SplitCommandArgs(input)
494 if _, ok := commands[inputCmd]; !ok {
495 messenger.Error("Unknown command ", inputCmd)
497 commands[inputCmd].action(args[1:])