]> git.lizzy.rs Git - micro.git/blob - cmd/micro/command.go
7193e56a3fe00559a3b8845d7ac06d735b41dd80
[micro.git] / cmd / micro / command.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "os"
9         "os/exec"
10         "os/signal"
11         "regexp"
12         "strings"
13
14         "github.com/mitchellh/go-homedir"
15 )
16
17 type Command struct {
18         action      func([]string)
19         completions []Completion
20 }
21
22 type StrCommand struct {
23         action      string
24         completions []Completion
25 }
26
27 var commands map[string]Command
28
29 var commandActions map[string]func([]string)
30
31 func init() {
32         commandActions = map[string]func([]string){
33                 "Set":       Set,
34                 "SetLocal":  SetLocal,
35                 "Show":      Show,
36                 "Run":       Run,
37                 "Bind":      Bind,
38                 "Quit":      Quit,
39                 "Save":      Save,
40                 "Replace":   Replace,
41                 "VSplit":    VSplit,
42                 "HSplit":    HSplit,
43                 "Tab":       NewTab,
44                 "Help":      Help,
45                 "Eval":      Eval,
46                 "ToggleLog": ToggleLog,
47                 "Plugin":    PluginCmd,
48                 "Reload":    Reload,
49         }
50 }
51
52 // InitCommands initializes the default commands
53 func InitCommands() {
54         commands = make(map[string]Command)
55
56         defaults := DefaultCommands()
57         parseCommands(defaults)
58 }
59
60 func parseCommands(userCommands map[string]StrCommand) {
61         for k, v := range userCommands {
62                 MakeCommand(k, v.action, v.completions...)
63         }
64 }
65
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)
74         }
75
76         commands[name] = Command{action, completions}
77 }
78
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}},
98         }
99 }
100
101 // PluginCmd installs, removes, updates, lists, or searches for given plugins
102 func PluginCmd(args []string) {
103         if len(args) >= 1 {
104                 switch args[0] {
105                 case "install":
106                         installedVersions := GetInstalledVersions(false)
107                         for _, plugin := range args[1:] {
108                                 pp := GetAllPluginPackages().Get(plugin)
109                                 if pp == nil {
110                                         messenger.Error("Unknown plugin \"" + plugin + "\"")
111                                 } else if err := pp.IsInstallable(); err != nil {
112                                         messenger.Error("Error installing ", plugin, ": ", err)
113                                 } else {
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")
118                                                         } else {
119                                                                 messenger.Error(pp.Name, " is already installed")
120                                                         }
121                                                 }
122                                         }
123                                         pp.Install()
124                                 }
125                         }
126                 case "remove":
127                         removed := ""
128                         for _, plugin := range args[1:] {
129                                 // check if the plugin exists.
130                                 for _, lp := range loadedPlugins {
131                                         if lp == plugin {
132                                                 UninstallPlugin(plugin)
133                                                 removed += plugin + " "
134                                                 continue
135                                         }
136                                 }
137                         }
138                         if !IsSpaces(removed) {
139                                 messenger.Message("Removed ", removed)
140                         } else {
141                                 messenger.Error("The requested plugins do not exist")
142                         }
143                 case "update":
144                         UpdatePlugins(args[1:])
145                 case "list":
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))
151                         }
152                         messenger.AddLog("----------------")
153                         if len(plugins) > 0 {
154                                 if CurView().Type != vtLog {
155                                         ToggleLog([]string{})
156                                 }
157                         }
158                 case "search":
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())
164                         }
165                         messenger.AddLog("----------------")
166                         if len(plugins) > 0 {
167                                 if CurView().Type != vtLog {
168                                         ToggleLog([]string{})
169                                 }
170                         }
171                 case "available":
172                         packages := GetAllPluginPackages()
173                         messenger.AddLog("Available Plugins:")
174                         for _, pkg := range packages {
175                                 messenger.AddLog(pkg.Name)
176                         }
177                         if CurView().Type != vtLog {
178                                 ToggleLog([]string{})
179                         }
180                 }
181         } else {
182                 messenger.Error("Not enough arguments")
183         }
184 }
185
186 func ToggleLog(args []string) {
187         buffer := messenger.getBuffer()
188         if CurView().Type != vtLog {
189                 CurView().HSplit(buffer)
190                 CurView().Type = vtLog
191                 RedrawAll()
192                 buffer.Cursor.Loc = buffer.Start()
193                 CurView().Relocate()
194                 buffer.Cursor.Loc = buffer.End()
195                 CurView().Relocate()
196         } else {
197                 CurView().Quit(true)
198         }
199 }
200
201 func Reload(args []string) {
202         LoadAll()
203 }
204
205 // Help tries to open the given help page in a horizontal split
206 func Help(args []string) {
207         if len(args) < 1 {
208                 // Open the default help if the user just typed "> help"
209                 CurView().openHelp("help")
210         } else {
211                 helpPage := args[0]
212                 if FindRuntimeFile(RTHelp, helpPage) != nil {
213                         CurView().openHelp(helpPage)
214                 } else {
215                         messenger.Error("Sorry, no help for ", helpPage)
216                 }
217         }
218 }
219
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) {
223         if len(args) == 0 {
224                 CurView().VSplit(NewBuffer([]byte{}, ""))
225         } else {
226                 filename := args[0]
227                 home, _ := homedir.Dir()
228                 filename = strings.Replace(filename, "~", home, 1)
229                 file, err := ioutil.ReadFile(filename)
230
231                 var buf *Buffer
232                 if err != nil {
233                         // File does not exist -- create an empty buffer with that name
234                         buf = NewBuffer([]byte{}, filename)
235                 } else {
236                         buf = NewBuffer(file, filename)
237                 }
238                 CurView().VSplit(buf)
239         }
240 }
241
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) {
245         if len(args) == 0 {
246                 CurView().HSplit(NewBuffer([]byte{}, ""))
247         } else {
248                 filename := args[0]
249                 home, _ := homedir.Dir()
250                 filename = strings.Replace(filename, "~", home, 1)
251                 file, err := ioutil.ReadFile(filename)
252
253                 var buf *Buffer
254                 if err != nil {
255                         // File does not exist -- create an empty buffer with that name
256                         buf = NewBuffer([]byte{}, filename)
257                 } else {
258                         buf = NewBuffer(file, filename)
259                 }
260                 CurView().HSplit(buf)
261         }
262 }
263
264 // Eval evaluates a lua expression
265 func Eval(args []string) {
266         if len(args) >= 1 {
267                 err := L.DoString(args[0])
268                 if err != nil {
269                         messenger.Error(err)
270                 }
271         } else {
272                 messenger.Error("Not enough arguments")
273         }
274 }
275
276 // NewTab opens the given file in a new tab
277 func NewTab(args []string) {
278         if len(args) == 0 {
279                 CurView().AddTab(true)
280         } else {
281                 filename := args[0]
282                 home, _ := homedir.Dir()
283                 filename = strings.Replace(filename, "~", home, 1)
284                 file, _ := ioutil.ReadFile(filename)
285
286                 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
287                 tab.SetNum(len(tabs))
288                 tabs = append(tabs, tab)
289                 curTab++
290                 if len(tabs) == 2 {
291                         for _, t := range tabs {
292                                 for _, v := range t.views {
293                                         v.ToggleTabbar()
294                                 }
295                         }
296                 }
297         }
298 }
299
300 // Set sets an option
301 func Set(args []string) {
302         if len(args) < 2 {
303                 messenger.Error("Not enough arguments")
304                 return
305         }
306
307         option := strings.TrimSpace(args[0])
308         value := strings.TrimSpace(args[1])
309
310         SetOptionAndSettings(option, value)
311 }
312
313 // SetLocal sets an option local to the buffer
314 func SetLocal(args []string) {
315         if len(args) < 2 {
316                 messenger.Error("Not enough arguments")
317                 return
318         }
319
320         option := strings.TrimSpace(args[0])
321         value := strings.TrimSpace(args[1])
322
323         err := SetLocalOption(option, value, CurView())
324         if err != nil {
325                 messenger.Error(err.Error())
326         }
327 }
328
329 // Show shows the value of the given option
330 func Show(args []string) {
331         if len(args) < 1 {
332                 messenger.Error("Please provide an option to show")
333                 return
334         }
335
336         option := GetOption(args[0])
337
338         if option == nil {
339                 messenger.Error(args[0], " is not a valid option")
340                 return
341         }
342
343         messenger.Message(option)
344 }
345
346 // Bind creates a new keybinding
347 func Bind(args []string) {
348         if len(args) < 2 {
349                 messenger.Error("Not enough arguments")
350                 return
351         }
352         BindKey(args[0], args[1])
353 }
354
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)
359 }
360
361 // Quit closes the main view
362 func Quit(args []string) {
363         // Close the main view
364         CurView().Quit(true)
365 }
366
367 // Save saves the buffer in the main view
368 func Save(args []string) {
369         if len(args) == 0 {
370                 // Save the main view
371                 CurView().Save(true)
372         } else {
373                 CurView().Buf.SaveAs(args[0])
374         }
375 }
376
377 // Replace runs search and replace
378 func Replace(args []string) {
379         if len(args) < 2 {
380                 // We need to find both a search and replace expression
381                 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
382                 return
383         }
384
385         var flags string
386         if len(args) == 3 {
387                 // The user included some flags
388                 flags = args[2]
389         }
390
391         search := string(args[0])
392         replace := string(args[1])
393
394         regex, err := regexp.Compile("(?m)" + search)
395         if err != nil {
396                 // There was an error with the user's regex
397                 messenger.Error(err.Error())
398                 return
399         }
400
401         view := CurView()
402
403         found := 0
404         if strings.Contains(flags, "c") {
405                 for {
406                         // The 'check' flag was used
407                         Search(search, view, true)
408                         if !view.Cursor.HasSelection() {
409                                 break
410                         }
411                         view.Relocate()
412                         if view.Buf.Settings["syntax"].(bool) {
413                                 view.matches = Match(view)
414                         }
415                         RedrawAll()
416                         choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
417                         if canceled {
418                                 if view.Cursor.HasSelection() {
419                                         view.Cursor.Loc = view.Cursor.CurSelection[0]
420                                         view.Cursor.ResetSelection()
421                                 }
422                                 messenger.Reset()
423                                 break
424                         }
425                         if choice {
426                                 view.Cursor.DeleteSelection()
427                                 view.Buf.Insert(view.Cursor.Loc, replace)
428                                 view.Cursor.ResetSelection()
429                                 messenger.Reset()
430                                 found++
431                         } else {
432                                 if view.Cursor.HasSelection() {
433                                         searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
434                                 } else {
435                                         searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
436                                 }
437                                 continue
438                         }
439                 }
440         } else {
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:] {
452                                         found++
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
460                                 }
461                         }
462                 }
463         }
464         view.Cursor.Relocate()
465
466         if found > 1 {
467                 messenger.Message("Replaced ", found, " occurrences of ", search)
468         } else if found == 1 {
469                 messenger.Message("Replaced ", found, " occurrence of ", search)
470         } else {
471                 messenger.Message("Nothing matched ", search)
472         }
473 }
474
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:]
479
480         cmd := exec.Command(inputCmd, args...)
481         outputBytes := &bytes.Buffer{}
482         cmd.Stdout = outputBytes
483         cmd.Stderr = outputBytes
484         cmd.Start()
485         err := cmd.Wait() // wait for command to finish
486         outstring := outputBytes.String()
487         return outstring, err
488 }
489
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]
495         if !openTerm {
496                 // Simply run the command in the background and notify the user when it's done
497                 messenger.Message("Running...")
498                 go func() {
499                         output, err := RunShellCommand(input)
500                         totalLines := strings.Split(output, "\n")
501
502                         if len(totalLines) < 3 {
503                                 if err == nil {
504                                         messenger.Message(inputCmd, " exited without error")
505                                 } else {
506                                         messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
507                                 }
508                         } else {
509                                 messenger.Message(output)
510                         }
511                         // We have to make sure to redraw
512                         RedrawAll()
513                 }()
514         } else {
515                 // Shut down the screen because we're going to interact directly with the shell
516                 screen.Fini()
517                 screen = nil
518
519                 args := SplitCommandArgs(input)[1:]
520
521                 // Set up everything for the command
522                 var outputBuf bytes.Buffer
523                 cmd := exec.Command(inputCmd, args...)
524                 cmd.Stdin = os.Stdin
525                 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
526                 cmd.Stderr = os.Stderr
527
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)
532                 go func() {
533                         for range c {
534                                 cmd.Process.Kill()
535                         }
536                 }()
537
538                 cmd.Start()
539                 err := cmd.Wait()
540
541                 output := outputBuf.String()
542                 if err != nil {
543                         output = err.Error()
544                 }
545
546                 if waitToFinish {
547                         // This is just so we don't return right away and let the user press enter to return
548                         TermMessage("")
549                 }
550
551                 // Start the screen back up
552                 InitScreen()
553
554                 return output
555         }
556         return ""
557 }
558
559 // HandleCommand handles input from the user
560 func HandleCommand(input string) {
561         args := SplitCommandArgs(input)
562         inputCmd := args[0]
563
564         if _, ok := commands[inputCmd]; !ok {
565                 messenger.Error("Unknown command ", inputCmd)
566         } else {
567                 commands[inputCmd].action(args[1:])
568         }
569 }