]> git.lizzy.rs Git - micro.git/blob - cmd/micro/command.go
Merge pull request #507 from NicolaiSoeborg/master
[micro.git] / cmd / micro / command.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io"
7         "os"
8         "os/exec"
9         "os/signal"
10         "path/filepath"
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                 "Cd":        Cd,
50                 "Pwd":       Pwd,
51                 "Open":      Open,
52         }
53 }
54
55 // InitCommands initializes the default commands
56 func InitCommands() {
57         commands = make(map[string]Command)
58
59         defaults := DefaultCommands()
60         parseCommands(defaults)
61 }
62
63 func parseCommands(userCommands map[string]StrCommand) {
64         for k, v := range userCommands {
65                 MakeCommand(k, v.action, v.completions...)
66         }
67 }
68
69 // MakeCommand is a function to easily create new commands
70 // This can be called by plugins in Lua so that plugins can define their own commands
71 func MakeCommand(name, function string, completions ...Completion) {
72         action := commandActions[function]
73         if _, ok := commandActions[function]; !ok {
74                 // If the user seems to be binding a function that doesn't exist
75                 // We hope that it's a lua function that exists and bind it to that
76                 action = LuaFunctionCommand(function)
77         }
78
79         commands[name] = Command{action, completions}
80 }
81
82 // DefaultCommands returns a map containing micro's default commands
83 func DefaultCommands() map[string]StrCommand {
84         return map[string]StrCommand{
85                 "set":      {"Set", []Completion{OptionCompletion, NoCompletion}},
86                 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
87                 "show":     {"Show", []Completion{OptionCompletion, NoCompletion}},
88                 "bind":     {"Bind", []Completion{NoCompletion}},
89                 "run":      {"Run", []Completion{NoCompletion}},
90                 "quit":     {"Quit", []Completion{NoCompletion}},
91                 "save":     {"Save", []Completion{NoCompletion}},
92                 "replace":  {"Replace", []Completion{NoCompletion}},
93                 "vsplit":   {"VSplit", []Completion{FileCompletion, NoCompletion}},
94                 "hsplit":   {"HSplit", []Completion{FileCompletion, NoCompletion}},
95                 "tab":      {"Tab", []Completion{FileCompletion, NoCompletion}},
96                 "help":     {"Help", []Completion{HelpCompletion, NoCompletion}},
97                 "eval":     {"Eval", []Completion{NoCompletion}},
98                 "log":      {"ToggleLog", []Completion{NoCompletion}},
99                 "plugin":   {"Plugin", []Completion{PluginCmdCompletion, PluginNameCompletion}},
100                 "reload":   {"Reload", []Completion{NoCompletion}},
101                 "cd":       {"Cd", []Completion{FileCompletion}},
102                 "pwd":      {"Pwd", []Completion{NoCompletion}},
103                 "open":     {"Open", []Completion{FileCompletion}},
104         }
105 }
106
107 // PluginCmd installs, removes, updates, lists, or searches for given plugins
108 func PluginCmd(args []string) {
109         if len(args) >= 1 {
110                 switch args[0] {
111                 case "install":
112                         installedVersions := GetInstalledVersions(false)
113                         for _, plugin := range args[1:] {
114                                 pp := GetAllPluginPackages().Get(plugin)
115                                 if pp == nil {
116                                         messenger.Error("Unknown plugin \"" + plugin + "\"")
117                                 } else if err := pp.IsInstallable(); err != nil {
118                                         messenger.Error("Error installing ", plugin, ": ", err)
119                                 } else {
120                                         for _, installed := range installedVersions {
121                                                 if pp.Name == installed.pack.Name {
122                                                         if pp.Versions[0].Version.Compare(installed.Version) == 1 {
123                                                                 messenger.Error(pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
124                                                         } else {
125                                                                 messenger.Error(pp.Name, " is already installed")
126                                                         }
127                                                 }
128                                         }
129                                         pp.Install()
130                                 }
131                         }
132                 case "remove":
133                         removed := ""
134                         for _, plugin := range args[1:] {
135                                 // check if the plugin exists.
136                                 if _, ok := loadedPlugins[plugin]; ok {
137                                         UninstallPlugin(plugin)
138                                         removed += plugin + " "
139                                         continue
140                                 }
141                         }
142                         if !IsSpaces(removed) {
143                                 messenger.Message("Removed ", removed)
144                         } else {
145                                 messenger.Error("The requested plugins do not exist")
146                         }
147                 case "update":
148                         UpdatePlugins(args[1:])
149                 case "list":
150                         plugins := GetInstalledVersions(false)
151                         messenger.AddLog("----------------")
152                         messenger.AddLog("The following plugins are currently installed:\n")
153                         for _, p := range plugins {
154                                 messenger.AddLog(fmt.Sprintf("%s (%s)", p.pack.Name, p.Version))
155                         }
156                         messenger.AddLog("----------------")
157                         if len(plugins) > 0 {
158                                 if CurView().Type != vtLog {
159                                         ToggleLog([]string{})
160                                 }
161                         }
162                 case "search":
163                         plugins := SearchPlugin(args[1:])
164                         messenger.Message(len(plugins), " plugins found")
165                         for _, p := range plugins {
166                                 messenger.AddLog("----------------")
167                                 messenger.AddLog(p.String())
168                         }
169                         messenger.AddLog("----------------")
170                         if len(plugins) > 0 {
171                                 if CurView().Type != vtLog {
172                                         ToggleLog([]string{})
173                                 }
174                         }
175                 case "available":
176                         packages := GetAllPluginPackages()
177                         messenger.AddLog("Available Plugins:")
178                         for _, pkg := range packages {
179                                 messenger.AddLog(pkg.Name)
180                         }
181                         if CurView().Type != vtLog {
182                                 ToggleLog([]string{})
183                         }
184                 }
185         } else {
186                 messenger.Error("Not enough arguments")
187         }
188 }
189
190 func Cd(args []string) {
191         if len(args) > 0 {
192                 home, _ := homedir.Dir()
193                 path := strings.Replace(args[0], "~", home, 1)
194                 os.Chdir(path)
195                 for _, tab := range tabs {
196                         for _, view := range tab.views {
197                                 wd, _ := os.Getwd()
198                                 view.Buf.Path, _ = MakeRelative(view.Buf.AbsPath, wd)
199                                 if p, _ := filepath.Abs(view.Buf.Path); !strings.Contains(p, wd) {
200                                         view.Buf.Path = view.Buf.AbsPath
201                                 }
202                         }
203                 }
204         }
205 }
206
207 func Pwd(args []string) {
208         wd, err := os.Getwd()
209         if err != nil {
210                 messenger.Message(err.Error())
211         } else {
212                 messenger.Message(wd)
213         }
214 }
215
216 func Open(args []string) {
217         if len(args) > 0 {
218                 filename := args[0]
219                 // the filename might or might not be quoted, so unquote first then join the strings.
220                 filename = strings.Join(SplitCommandArgs(filename), " ")
221
222                 CurView().Open(filename)
223         } else {
224                 messenger.Error("No filename")
225         }
226 }
227
228 func ToggleLog(args []string) {
229         buffer := messenger.getBuffer()
230         if CurView().Type != vtLog {
231                 CurView().HSplit(buffer)
232                 CurView().Type = vtLog
233                 RedrawAll()
234                 buffer.Cursor.Loc = buffer.Start()
235                 CurView().Relocate()
236                 buffer.Cursor.Loc = buffer.End()
237                 CurView().Relocate()
238         } else {
239                 CurView().Quit(true)
240         }
241 }
242
243 func Reload(args []string) {
244         LoadAll()
245 }
246
247 // Help tries to open the given help page in a horizontal split
248 func Help(args []string) {
249         if len(args) < 1 {
250                 // Open the default help if the user just typed "> help"
251                 CurView().openHelp("help")
252         } else {
253                 helpPage := args[0]
254                 if FindRuntimeFile(RTHelp, helpPage) != nil {
255                         CurView().openHelp(helpPage)
256                 } else {
257                         messenger.Error("Sorry, no help for ", helpPage)
258                 }
259         }
260 }
261
262 // VSplit opens a vertical split with file given in the first argument
263 // If no file is given, it opens an empty buffer in a new split
264 func VSplit(args []string) {
265         if len(args) == 0 {
266                 CurView().VSplit(NewBuffer(strings.NewReader(""), ""))
267         } else {
268                 filename := args[0]
269                 home, _ := homedir.Dir()
270                 filename = strings.Replace(filename, "~", home, 1)
271                 file, err := os.Open(filename)
272                 defer file.Close()
273
274                 var buf *Buffer
275                 if err != nil {
276                         // File does not exist -- create an empty buffer with that name
277                         buf = NewBuffer(strings.NewReader(""), filename)
278                 } else {
279                         buf = NewBuffer(file, filename)
280                 }
281                 CurView().VSplit(buf)
282         }
283 }
284
285 // HSplit opens a horizontal split with file given in the first argument
286 // If no file is given, it opens an empty buffer in a new split
287 func HSplit(args []string) {
288         if len(args) == 0 {
289                 CurView().HSplit(NewBuffer(strings.NewReader(""), ""))
290         } else {
291                 filename := args[0]
292                 home, _ := homedir.Dir()
293                 filename = strings.Replace(filename, "~", home, 1)
294                 file, err := os.Open(filename)
295                 defer file.Close()
296
297                 var buf *Buffer
298                 if err != nil {
299                         // File does not exist -- create an empty buffer with that name
300                         buf = NewBuffer(strings.NewReader(""), filename)
301                 } else {
302                         buf = NewBuffer(file, filename)
303                 }
304                 CurView().HSplit(buf)
305         }
306 }
307
308 // Eval evaluates a lua expression
309 func Eval(args []string) {
310         if len(args) >= 1 {
311                 err := L.DoString(args[0])
312                 if err != nil {
313                         messenger.Error(err)
314                 }
315         } else {
316                 messenger.Error("Not enough arguments")
317         }
318 }
319
320 // NewTab opens the given file in a new tab
321 func NewTab(args []string) {
322         if len(args) == 0 {
323                 CurView().AddTab(true)
324         } else {
325                 filename := args[0]
326                 home, _ := homedir.Dir()
327                 filename = strings.Replace(filename, "~", home, 1)
328                 file, _ := os.Open(filename)
329                 defer file.Close()
330
331                 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
332                 tab.SetNum(len(tabs))
333                 tabs = append(tabs, tab)
334                 curTab = len(tabs) - 1
335                 if len(tabs) == 2 {
336                         for _, t := range tabs {
337                                 for _, v := range t.views {
338                                         v.ToggleTabbar()
339                                 }
340                         }
341                 }
342         }
343 }
344
345 // Set sets an option
346 func Set(args []string) {
347         if len(args) < 2 {
348                 messenger.Error("Not enough arguments")
349                 return
350         }
351
352         option := strings.TrimSpace(args[0])
353         value := strings.TrimSpace(args[1])
354
355         SetOptionAndSettings(option, value)
356 }
357
358 // SetLocal sets an option local to the buffer
359 func SetLocal(args []string) {
360         if len(args) < 2 {
361                 messenger.Error("Not enough arguments")
362                 return
363         }
364
365         option := strings.TrimSpace(args[0])
366         value := strings.TrimSpace(args[1])
367
368         err := SetLocalOption(option, value, CurView())
369         if err != nil {
370                 messenger.Error(err.Error())
371         }
372 }
373
374 // Show shows the value of the given option
375 func Show(args []string) {
376         if len(args) < 1 {
377                 messenger.Error("Please provide an option to show")
378                 return
379         }
380
381         option := GetOption(args[0])
382
383         if option == nil {
384                 messenger.Error(args[0], " is not a valid option")
385                 return
386         }
387
388         messenger.Message(option)
389 }
390
391 // Bind creates a new keybinding
392 func Bind(args []string) {
393         if len(args) < 2 {
394                 messenger.Error("Not enough arguments")
395                 return
396         }
397         BindKey(args[0], args[1])
398 }
399
400 // Run runs a shell command in the background
401 func Run(args []string) {
402         // Run a shell command in the background (openTerm is false)
403         HandleShellCommand(JoinCommandArgs(args...), false, true)
404 }
405
406 // Quit closes the main view
407 func Quit(args []string) {
408         // Close the main view
409         CurView().Quit(true)
410 }
411
412 // Save saves the buffer in the main view
413 func Save(args []string) {
414         if len(args) == 0 {
415                 // Save the main view
416                 CurView().Save(true)
417         } else {
418                 CurView().Buf.SaveAs(args[0])
419         }
420 }
421
422 // Replace runs search and replace
423 func Replace(args []string) {
424         if len(args) < 2 {
425                 // We need to find both a search and replace expression
426                 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
427                 return
428         }
429
430         var flags string
431         if len(args) == 3 {
432                 // The user included some flags
433                 flags = args[2]
434         }
435
436         search := string(args[0])
437         replace := string(args[1])
438
439         regex, err := regexp.Compile("(?m)" + search)
440         if err != nil {
441                 // There was an error with the user's regex
442                 messenger.Error(err.Error())
443                 return
444         }
445
446         view := CurView()
447
448         found := 0
449         if strings.Contains(flags, "c") {
450                 for {
451                         // The 'check' flag was used
452                         Search(search, view, true)
453                         if !view.Cursor.HasSelection() {
454                                 break
455                         }
456                         view.Relocate()
457                         if view.Buf.Settings["syntax"].(bool) {
458                                 view.matches = Match(view)
459                         }
460                         RedrawAll()
461                         choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
462                         if canceled {
463                                 if view.Cursor.HasSelection() {
464                                         view.Cursor.Loc = view.Cursor.CurSelection[0]
465                                         view.Cursor.ResetSelection()
466                                 }
467                                 messenger.Reset()
468                                 break
469                         }
470                         if choice {
471                                 view.Cursor.DeleteSelection()
472                                 view.Buf.Insert(view.Cursor.Loc, replace)
473                                 view.Cursor.ResetSelection()
474                                 messenger.Reset()
475                                 found++
476                         } else {
477                                 if view.Cursor.HasSelection() {
478                                         searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
479                                 } else {
480                                         searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
481                                 }
482                                 continue
483                         }
484                 }
485         } else {
486                 bufStr := view.Buf.String()
487                 matches := regex.FindAllStringIndex(bufStr, -1)
488                 if matches != nil && len(matches) > 0 {
489                         prevMatchCount := runePos(matches[0][0], bufStr)
490                         searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
491                         from := FromCharPos(matches[0][0], view.Buf)
492                         to := from.Move(searchCount, view.Buf)
493                         adjust := Count(replace) - searchCount
494                         view.Buf.Replace(from, to, replace)
495                         if len(matches) > 1 {
496                                 for _, match := range matches[1:] {
497                                         found++
498                                         matchCount := runePos(match[0], bufStr)
499                                         searchCount = runePos(match[1], bufStr) - matchCount
500                                         from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
501                                         to = from.Move(searchCount, view.Buf)
502                                         view.Buf.Replace(from, to, replace)
503                                         prevMatchCount = matchCount
504                                         adjust = Count(replace) - searchCount
505                                 }
506                         }
507                 }
508         }
509         view.Cursor.Relocate()
510
511         if found > 1 {
512                 messenger.Message("Replaced ", found, " occurrences of ", search)
513         } else if found == 1 {
514                 messenger.Message("Replaced ", found, " occurrence of ", search)
515         } else {
516                 messenger.Message("Nothing matched ", search)
517         }
518 }
519
520 // RunShellCommand executes a shell command and returns the output/error
521 func RunShellCommand(input string) (string, error) {
522         inputCmd := SplitCommandArgs(input)[0]
523         args := SplitCommandArgs(input)[1:]
524
525         cmd := exec.Command(inputCmd, args...)
526         outputBytes := &bytes.Buffer{}
527         cmd.Stdout = outputBytes
528         cmd.Stderr = outputBytes
529         cmd.Start()
530         err := cmd.Wait() // wait for command to finish
531         outstring := outputBytes.String()
532         return outstring, err
533 }
534
535 // HandleShellCommand runs the shell command
536 // The openTerm argument specifies whether a terminal should be opened (for viewing output
537 // or interacting with stdin)
538 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
539         inputCmd := SplitCommandArgs(input)[0]
540         if !openTerm {
541                 // Simply run the command in the background and notify the user when it's done
542                 messenger.Message("Running...")
543                 go func() {
544                         output, err := RunShellCommand(input)
545                         totalLines := strings.Split(output, "\n")
546
547                         if len(totalLines) < 3 {
548                                 if err == nil {
549                                         messenger.Message(inputCmd, " exited without error")
550                                 } else {
551                                         messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
552                                 }
553                         } else {
554                                 messenger.Message(output)
555                         }
556                         // We have to make sure to redraw
557                         RedrawAll()
558                 }()
559         } else {
560                 // Shut down the screen because we're going to interact directly with the shell
561                 screen.Fini()
562                 screen = nil
563
564                 args := SplitCommandArgs(input)[1:]
565
566                 // Set up everything for the command
567                 var outputBuf bytes.Buffer
568                 cmd := exec.Command(inputCmd, args...)
569                 cmd.Stdin = os.Stdin
570                 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
571                 cmd.Stderr = os.Stderr
572
573                 // This is a trap for Ctrl-C so that it doesn't kill micro
574                 // Instead we trap Ctrl-C to kill the program we're running
575                 c := make(chan os.Signal, 1)
576                 signal.Notify(c, os.Interrupt)
577                 go func() {
578                         for range c {
579                                 cmd.Process.Kill()
580                         }
581                 }()
582
583                 cmd.Start()
584                 err := cmd.Wait()
585
586                 output := outputBuf.String()
587                 if err != nil {
588                         output = err.Error()
589                 }
590
591                 if waitToFinish {
592                         // This is just so we don't return right away and let the user press enter to return
593                         TermMessage("")
594                 }
595
596                 // Start the screen back up
597                 InitScreen()
598
599                 return output
600         }
601         return ""
602 }
603
604 // HandleCommand handles input from the user
605 func HandleCommand(input string) {
606         args := SplitCommandArgs(input)
607         inputCmd := args[0]
608
609         if _, ok := commands[inputCmd]; !ok {
610                 messenger.Error("Unknown command ", inputCmd)
611         } else {
612                 commands[inputCmd].action(args[1:])
613         }
614 }