]> git.lizzy.rs Git - micro.git/blob - cmd/micro/command.go
e43b38137bcafbab4938037613f9f759288a2a3b
[micro.git] / cmd / micro / command.go
1 package main
2
3 import (
4         "bytes"
5         "io"
6         "io/ioutil"
7         "os"
8         "os/exec"
9         "os/signal"
10         "regexp"
11         "strings"
12
13         "github.com/mitchellh/go-homedir"
14 )
15
16 type Command struct {
17         action      func([]string)
18         completions []Completion
19 }
20
21 type StrCommand struct {
22         action      string
23         completions []Completion
24 }
25
26 var commands map[string]Command
27
28 var commandActions = map[string]func([]string){
29         "Set":       Set,
30         "SetLocal":  SetLocal,
31         "Show":      Show,
32         "Run":       Run,
33         "Bind":      Bind,
34         "Quit":      Quit,
35         "Save":      Save,
36         "Replace":   Replace,
37         "VSplit":    VSplit,
38         "HSplit":    HSplit,
39         "Tab":       NewTab,
40         "Help":      Help,
41         "Eval":      Eval,
42         "ToggleLog": ToggleLog,
43         "Plugin":    PluginCmd,
44 }
45
46 // InitCommands initializes the default commands
47 func InitCommands() {
48         commands = make(map[string]Command)
49
50         defaults := DefaultCommands()
51         parseCommands(defaults)
52 }
53
54 func parseCommands(userCommands map[string]StrCommand) {
55         for k, v := range userCommands {
56                 MakeCommand(k, v.action, v.completions...)
57         }
58 }
59
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)
68         }
69
70         commands[name] = Command{action, completions}
71 }
72
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}},
91         }
92 }
93
94 // InstallPlugin installs the given plugin by exact name match
95 func PluginCmd(args []string) {
96         if len(args) >= 1 {
97                 switch args[0] {
98                 case "install":
99                         for _, plugin := range args[1:] {
100                                 pp := GetAllPluginPackages().Get(plugin)
101                                 if pp == nil {
102                                         messenger.Error("Unknown plugin \"" + plugin + "\"")
103                                 } else if !pp.IsInstallable() {
104                                         messenger.Error("Plugin \"" + plugin + "\" can not be installed.")
105                                 } else {
106                                         pp.Install()
107                                 }
108                         }
109                 case "remove":
110                         for _, plugin := range args[1:] {
111                                 // check if the plugin exists.
112                                 for _, lp := range loadedPlugins {
113                                         if lp == plugin {
114                                                 UninstallPlugin(plugin)
115                                                 continue
116                                         }
117                                 }
118                         }
119                 case "update":
120                         UpdatePlugins()
121                 }
122         } else {
123                 messenger.Error("Not enough arguments")
124         }
125 }
126
127 func ToggleLog(args []string) {
128         buffer := messenger.getBuffer()
129         if CurView().Type != vtLog {
130                 CurView().HSplit(buffer)
131                 CurView().Type = vtLog
132         } else {
133                 CurView().Quit(true)
134         }
135 }
136
137 // Help tries to open the given help page in a horizontal split
138 func Help(args []string) {
139         if len(args) < 1 {
140                 // Open the default help if the user just typed "> help"
141                 CurView().openHelp("help")
142         } else {
143                 helpPage := args[0]
144                 if FindRuntimeFile(RTHelp, helpPage) != nil {
145                         CurView().openHelp(helpPage)
146                 } else {
147                         messenger.Error("Sorry, no help for ", helpPage)
148                 }
149         }
150 }
151
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) {
155         if len(args) == 0 {
156                 CurView().VSplit(NewBuffer([]byte{}, ""))
157         } else {
158                 filename := args[0]
159                 home, _ := homedir.Dir()
160                 filename = strings.Replace(filename, "~", home, 1)
161                 file, err := ioutil.ReadFile(filename)
162
163                 var buf *Buffer
164                 if err != nil {
165                         // File does not exist -- create an empty buffer with that name
166                         buf = NewBuffer([]byte{}, filename)
167                 } else {
168                         buf = NewBuffer(file, filename)
169                 }
170                 CurView().VSplit(buf)
171         }
172 }
173
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) {
177         if len(args) == 0 {
178                 CurView().HSplit(NewBuffer([]byte{}, ""))
179         } else {
180                 filename := args[0]
181                 home, _ := homedir.Dir()
182                 filename = strings.Replace(filename, "~", home, 1)
183                 file, err := ioutil.ReadFile(filename)
184
185                 var buf *Buffer
186                 if err != nil {
187                         // File does not exist -- create an empty buffer with that name
188                         buf = NewBuffer([]byte{}, filename)
189                 } else {
190                         buf = NewBuffer(file, filename)
191                 }
192                 CurView().HSplit(buf)
193         }
194 }
195
196 // Eval evaluates a lua expression
197 func Eval(args []string) {
198         if len(args) >= 1 {
199                 err := L.DoString(args[0])
200                 if err != nil {
201                         messenger.Error(err)
202                 }
203         } else {
204                 messenger.Error("Not enough arguments")
205         }
206 }
207
208 // NewTab opens the given file in a new tab
209 func NewTab(args []string) {
210         if len(args) == 0 {
211                 CurView().AddTab(true)
212         } else {
213                 filename := args[0]
214                 home, _ := homedir.Dir()
215                 filename = strings.Replace(filename, "~", home, 1)
216                 file, _ := ioutil.ReadFile(filename)
217
218                 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
219                 tab.SetNum(len(tabs))
220                 tabs = append(tabs, tab)
221                 curTab++
222                 if len(tabs) == 2 {
223                         for _, t := range tabs {
224                                 for _, v := range t.views {
225                                         v.ToggleTabbar()
226                                 }
227                         }
228                 }
229         }
230 }
231
232 // Set sets an option
233 func Set(args []string) {
234         if len(args) < 2 {
235                 messenger.Error("Not enough arguments")
236                 return
237         }
238
239         option := strings.TrimSpace(args[0])
240         value := strings.TrimSpace(args[1])
241
242         SetOptionAndSettings(option, value)
243 }
244
245 // SetLocal sets an option local to the buffer
246 func SetLocal(args []string) {
247         if len(args) < 2 {
248                 messenger.Error("Not enough arguments")
249                 return
250         }
251
252         option := strings.TrimSpace(args[0])
253         value := strings.TrimSpace(args[1])
254
255         err := SetLocalOption(option, value, CurView())
256         if err != nil {
257                 messenger.Error(err.Error())
258         }
259 }
260
261 // Show shows the value of the given option
262 func Show(args []string) {
263         if len(args) < 1 {
264                 messenger.Error("Please provide an option to show")
265                 return
266         }
267
268         option := GetOption(args[0])
269
270         if option == nil {
271                 messenger.Error(args[0], " is not a valid option")
272                 return
273         }
274
275         messenger.Message(option)
276 }
277
278 // Bind creates a new keybinding
279 func Bind(args []string) {
280         if len(args) < 2 {
281                 messenger.Error("Not enough arguments")
282                 return
283         }
284         BindKey(args[0], args[1])
285 }
286
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)
291 }
292
293 // Quit closes the main view
294 func Quit(args []string) {
295         // Close the main view
296         CurView().Quit(true)
297 }
298
299 // Save saves the buffer in the main view
300 func Save(args []string) {
301         if len(args) == 0 {
302                 // Save the main view
303                 CurView().Save(true)
304         } else {
305                 CurView().Buf.SaveAs(args[0])
306         }
307 }
308
309 // Replace runs search and replace
310 func Replace(args []string) {
311         if len(args) < 2 {
312                 // We need to find both a search and replace expression
313                 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
314                 return
315         }
316
317         var flags string
318         if len(args) == 3 {
319                 // The user included some flags
320                 flags = args[2]
321         }
322
323         search := string(args[0])
324         replace := string(args[1])
325
326         regex, err := regexp.Compile(search)
327         if err != nil {
328                 // There was an error with the user's regex
329                 messenger.Error(err.Error())
330                 return
331         }
332
333         view := CurView()
334
335         found := 0
336         if strings.Contains(flags, "c") {
337                 for {
338                         // The 'check' flag was used
339                         Search(search, view, true)
340                         if !view.Cursor.HasSelection() {
341                                 break
342                         }
343                         view.Relocate()
344                         if view.Buf.Settings["syntax"].(bool) {
345                                 view.matches = Match(view)
346                         }
347                         RedrawAll()
348                         choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
349                         if canceled {
350                                 if view.Cursor.HasSelection() {
351                                         view.Cursor.Loc = view.Cursor.CurSelection[0]
352                                         view.Cursor.ResetSelection()
353                                 }
354                                 messenger.Reset()
355                                 break
356                         }
357                         if choice {
358                                 view.Cursor.DeleteSelection()
359                                 view.Buf.Insert(view.Cursor.Loc, replace)
360                                 view.Cursor.ResetSelection()
361                                 messenger.Reset()
362                                 found++
363                         } else {
364                                 if view.Cursor.HasSelection() {
365                                         searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
366                                 } else {
367                                         searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
368                                 }
369                                 continue
370                         }
371                 }
372         } else {
373                 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
374                 if matches != nil && len(matches) > 0 {
375                         adjust := 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:] {
383                                         found++
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)
388                                         prevMatch = match
389                                         // adjust += Count(replace) - Count(search)
390                                 }
391                         }
392                 }
393         }
394         view.Cursor.Relocate()
395
396         if found > 1 {
397                 messenger.Message("Replaced ", found, " occurrences of ", search)
398         } else if found == 1 {
399                 messenger.Message("Replaced ", found, " occurrence of ", search)
400         } else {
401                 messenger.Message("Nothing matched ", search)
402         }
403 }
404
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:]
409
410         cmd := exec.Command(inputCmd, args...)
411         outputBytes := &bytes.Buffer{}
412         cmd.Stdout = outputBytes
413         cmd.Stderr = outputBytes
414         cmd.Start()
415         err := cmd.Wait() // wait for command to finish
416         outstring := outputBytes.String()
417         return outstring, err
418 }
419
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]
425         if !openTerm {
426                 // Simply run the command in the background and notify the user when it's done
427                 messenger.Message("Running...")
428                 go func() {
429                         output, err := RunShellCommand(input)
430                         totalLines := strings.Split(output, "\n")
431
432                         if len(totalLines) < 3 {
433                                 if err == nil {
434                                         messenger.Message(inputCmd, " exited without error")
435                                 } else {
436                                         messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
437                                 }
438                         } else {
439                                 messenger.Message(output)
440                         }
441                         // We have to make sure to redraw
442                         RedrawAll()
443                 }()
444         } else {
445                 // Shut down the screen because we're going to interact directly with the shell
446                 screen.Fini()
447                 screen = nil
448
449                 args := SplitCommandArgs(input)[1:]
450
451                 // Set up everything for the command
452                 var outputBuf bytes.Buffer
453                 cmd := exec.Command(inputCmd, args...)
454                 cmd.Stdin = os.Stdin
455                 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
456                 cmd.Stderr = os.Stderr
457
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)
462                 go func() {
463                         for range c {
464                                 cmd.Process.Kill()
465                         }
466                 }()
467
468                 cmd.Start()
469                 err := cmd.Wait()
470
471                 output := outputBuf.String()
472                 if err != nil {
473                         output = err.Error()
474                 }
475
476                 if waitToFinish {
477                         // This is just so we don't return right away and let the user press enter to return
478                         TermMessage("")
479                 }
480
481                 // Start the screen back up
482                 InitScreen()
483
484                 return output
485         }
486         return ""
487 }
488
489 // HandleCommand handles input from the user
490 func HandleCommand(input string) {
491         args := SplitCommandArgs(input)
492         inputCmd := args[0]
493
494         if _, ok := commands[inputCmd]; !ok {
495                 messenger.Error("Unknown command ", inputCmd)
496         } else {
497                 commands[inputCmd].action(args[1:])
498         }
499 }