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,
45 // InitCommands initializes the default commands
47 commands = make(map[string]Command)
49 defaults := DefaultCommands()
50 parseCommands(defaults)
53 func parseCommands(userCommands map[string]StrCommand) {
54 for k, v := range userCommands {
55 MakeCommand(k, v.action, v.completions...)
59 // MakeCommand is a function to easily create new commands
60 // This can be called by plugins in Lua so that plugins can define their own commands
61 func MakeCommand(name, function string, completions ...Completion) {
62 action := commandActions[function]
63 if _, ok := commandActions[function]; !ok {
64 // If the user seems to be binding a function that doesn't exist
65 // We hope that it's a lua function that exists and bind it to that
66 action = LuaFunctionCommand(function)
69 commands[name] = Command{action, completions}
72 // DefaultCommands returns a map containing micro's default commands
73 func DefaultCommands() map[string]StrCommand {
74 return map[string]StrCommand{
75 "set": {"Set", []Completion{OptionCompletion, NoCompletion}},
76 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
77 "show": {"Show", []Completion{OptionCompletion, NoCompletion}},
78 "bind": {"Bind", []Completion{NoCompletion}},
79 "run": {"Run", []Completion{NoCompletion}},
80 "quit": {"Quit", []Completion{NoCompletion}},
81 "save": {"Save", []Completion{NoCompletion}},
82 "replace": {"Replace", []Completion{NoCompletion}},
83 "vsplit": {"VSplit", []Completion{FileCompletion, NoCompletion}},
84 "hsplit": {"HSplit", []Completion{FileCompletion, NoCompletion}},
85 "tab": {"Tab", []Completion{FileCompletion, NoCompletion}},
86 "help": {"Help", []Completion{HelpCompletion, NoCompletion}},
87 "eval": {"Eval", []Completion{NoCompletion}},
88 "log": {"ToggleLog", []Completion{NoCompletion}},
92 func ToggleLog(args []string) {
93 buffer := messenger.getBuffer()
94 if CurView().Type != vtLog {
95 CurView().VSplit(buffer)
96 CurView().Type = vtLog
102 // Help tries to open the given help page in a horizontal split
103 func Help(args []string) {
105 // Open the default help if the user just typed "> help"
106 CurView().openHelp("help")
109 if FindRuntimeFile(RTHelp, helpPage) != nil {
110 CurView().openHelp(helpPage)
112 messenger.Error("Sorry, no help for ", helpPage)
117 // VSplit opens a vertical split with file given in the first argument
118 // If no file is given, it opens an empty buffer in a new split
119 func VSplit(args []string) {
121 CurView().VSplit(NewBuffer([]byte{}, ""))
124 home, _ := homedir.Dir()
125 filename = strings.Replace(filename, "~", home, 1)
126 file, err := ioutil.ReadFile(filename)
130 // File does not exist -- create an empty buffer with that name
131 buf = NewBuffer([]byte{}, filename)
133 buf = NewBuffer(file, filename)
135 CurView().VSplit(buf)
139 // HSplit opens a horizontal split with file given in the first argument
140 // If no file is given, it opens an empty buffer in a new split
141 func HSplit(args []string) {
143 CurView().HSplit(NewBuffer([]byte{}, ""))
146 home, _ := homedir.Dir()
147 filename = strings.Replace(filename, "~", home, 1)
148 file, err := ioutil.ReadFile(filename)
152 // File does not exist -- create an empty buffer with that name
153 buf = NewBuffer([]byte{}, filename)
155 buf = NewBuffer(file, filename)
157 CurView().HSplit(buf)
161 // Eval evaluates a lua expression
162 func Eval(args []string) {
164 err := L.DoString(args[0])
169 messenger.Error("Not enough arguments")
173 // NewTab opens the given file in a new tab
174 func NewTab(args []string) {
176 CurView().AddTab(true)
179 home, _ := homedir.Dir()
180 filename = strings.Replace(filename, "~", home, 1)
181 file, _ := ioutil.ReadFile(filename)
183 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
184 tab.SetNum(len(tabs))
185 tabs = append(tabs, tab)
188 for _, t := range tabs {
189 for _, v := range t.views {
197 // Set sets an option
198 func Set(args []string) {
200 messenger.Error("Not enough arguments")
204 option := strings.TrimSpace(args[0])
205 value := strings.TrimSpace(args[1])
207 SetOptionAndSettings(option, value)
210 // SetLocal sets an option local to the buffer
211 func SetLocal(args []string) {
213 messenger.Error("Not enough arguments")
217 option := strings.TrimSpace(args[0])
218 value := strings.TrimSpace(args[1])
220 err := SetLocalOption(option, value, CurView())
222 messenger.Error(err.Error())
226 // Show shows the value of the given option
227 func Show(args []string) {
229 messenger.Error("Please provide an option to show")
233 option := GetOption(args[0])
236 messenger.Error(args[0], " is not a valid option")
240 messenger.Message(option)
243 // Bind creates a new keybinding
244 func Bind(args []string) {
246 messenger.Error("Not enough arguments")
249 BindKey(args[0], args[1])
252 // Run runs a shell command in the background
253 func Run(args []string) {
254 // Run a shell command in the background (openTerm is false)
255 HandleShellCommand(JoinCommandArgs(args...), false, true)
258 // Quit closes the main view
259 func Quit(args []string) {
260 // Close the main view
264 // Save saves the buffer in the main view
265 func Save(args []string) {
267 // Save the main view
270 CurView().Buf.SaveAs(args[0])
274 // Replace runs search and replace
275 func Replace(args []string) {
277 // We need to find both a search and replace expression
278 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
284 // The user included some flags
288 search := string(args[0])
289 replace := string(args[1])
291 regex, err := regexp.Compile(search)
293 // There was an error with the user's regex
294 messenger.Error(err.Error())
301 if strings.Contains(flags, "c") {
303 // The 'check' flag was used
304 Search(search, view, true)
305 if !view.Cursor.HasSelection() {
309 if view.Buf.Settings["syntax"].(bool) {
310 view.matches = Match(view)
313 choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
315 if view.Cursor.HasSelection() {
316 view.Cursor.Loc = view.Cursor.CurSelection[0]
317 view.Cursor.ResetSelection()
323 view.Cursor.DeleteSelection()
324 view.Buf.Insert(view.Cursor.Loc, replace)
325 view.Cursor.ResetSelection()
329 if view.Cursor.HasSelection() {
330 searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
332 searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
338 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
339 if matches != nil && len(matches) > 0 {
341 prevMatch := matches[0]
342 from := FromCharPos(prevMatch[0], view.Buf)
343 to := from.Move(Count(search), view.Buf)
344 adjust += Count(replace) - Count(search)
345 view.Buf.Replace(from, to, replace)
346 if len(matches) > 1 {
347 for _, match := range matches[1:] {
349 from = from.Move(match[0]-prevMatch[0]+adjust, view.Buf)
350 to := from.Move(Count(search), view.Buf)
351 // TermMessage(match[0], " ", prevMatch[0], " ", adjust, "\n", from, " ", to)
352 view.Buf.Replace(from, to, replace)
354 // adjust += Count(replace) - Count(search)
359 view.Cursor.Relocate()
362 messenger.Message("Replaced ", found, " occurrences of ", search)
363 } else if found == 1 {
364 messenger.Message("Replaced ", found, " occurrence of ", search)
366 messenger.Message("Nothing matched ", search)
370 // RunShellCommand executes a shell command and returns the output/error
371 func RunShellCommand(input string) (string, error) {
372 inputCmd := SplitCommandArgs(input)[0]
373 args := SplitCommandArgs(input)[1:]
375 cmd := exec.Command(inputCmd, args...)
376 outputBytes := &bytes.Buffer{}
377 cmd.Stdout = outputBytes
378 cmd.Stderr = outputBytes
380 err := cmd.Wait() // wait for command to finish
381 outstring := outputBytes.String()
382 return outstring, err
385 // HandleShellCommand runs the shell command
386 // The openTerm argument specifies whether a terminal should be opened (for viewing output
387 // or interacting with stdin)
388 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
389 inputCmd := SplitCommandArgs(input)[0]
391 // Simply run the command in the background and notify the user when it's done
392 messenger.Message("Running...")
394 output, err := RunShellCommand(input)
395 totalLines := strings.Split(output, "\n")
397 if len(totalLines) < 3 {
399 messenger.Message(inputCmd, " exited without error")
401 messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
404 messenger.Message(output)
406 // We have to make sure to redraw
410 // Shut down the screen because we're going to interact directly with the shell
414 args := SplitCommandArgs(input)[1:]
416 // Set up everything for the command
417 var outputBuf bytes.Buffer
418 cmd := exec.Command(inputCmd, args...)
420 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
421 cmd.Stderr = os.Stderr
423 // This is a trap for Ctrl-C so that it doesn't kill micro
424 // Instead we trap Ctrl-C to kill the program we're running
425 c := make(chan os.Signal, 1)
426 signal.Notify(c, os.Interrupt)
436 output := outputBuf.String()
442 // This is just so we don't return right away and let the user press enter to return
446 // Start the screen back up
454 // HandleCommand handles input from the user
455 func HandleCommand(input string) {
456 args := SplitCommandArgs(input)
459 if _, ok := commands[inputCmd]; !ok {
460 messenger.Error("Unknown command ", inputCmd)
462 commands[inputCmd].action(args[1:])