]> git.lizzy.rs Git - micro.git/blob - cmd/micro/command.go
Optimize search and replace a lot
[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 }
43
44 // InitCommands initializes the default commands
45 func InitCommands() {
46         commands = make(map[string]Command)
47
48         defaults := DefaultCommands()
49         parseCommands(defaults)
50 }
51
52 func parseCommands(userCommands map[string]StrCommand) {
53         for k, v := range userCommands {
54                 MakeCommand(k, v.action, v.completions...)
55         }
56 }
57
58 // MakeCommand is a function to easily create new commands
59 // This can be called by plugins in Lua so that plugins can define their own commands
60 func MakeCommand(name, function string, completions ...Completion) {
61         action := commandActions[function]
62         if _, ok := commandActions[function]; !ok {
63                 // If the user seems to be binding a function that doesn't exist
64                 // We hope that it's a lua function that exists and bind it to that
65                 action = LuaFunctionCommand(function)
66         }
67
68         commands[name] = Command{action, completions}
69 }
70
71 // DefaultCommands returns a map containing micro's default commands
72 func DefaultCommands() map[string]StrCommand {
73         return map[string]StrCommand{
74                 "set":      {"Set", []Completion{OptionCompletion, NoCompletion}},
75                 "setlocal": {"SetLocal", []Completion{OptionCompletion, NoCompletion}},
76                 "show":     {"Show", []Completion{OptionCompletion, NoCompletion}},
77                 "bind":     {"Bind", []Completion{NoCompletion}},
78                 "run":      {"Run", []Completion{NoCompletion}},
79                 "quit":     {"Quit", []Completion{NoCompletion}},
80                 "save":     {"Save", []Completion{NoCompletion}},
81                 "replace":  {"Replace", []Completion{NoCompletion}},
82                 "vsplit":   {"VSplit", []Completion{FileCompletion, NoCompletion}},
83                 "hsplit":   {"HSplit", []Completion{FileCompletion, NoCompletion}},
84                 "tab":      {"Tab", []Completion{FileCompletion, NoCompletion}},
85                 "help":     {"Help", []Completion{HelpCompletion, NoCompletion}},
86                 "eval":     {"Eval", []Completion{NoCompletion}},
87         }
88 }
89
90 // Help tries to open the given help page in a horizontal split
91 func Help(args []string) {
92         if len(args) < 1 {
93                 // Open the default help if the user just typed "> help"
94                 CurView().openHelp("help")
95         } else {
96                 helpPage := args[0]
97                 if _, ok := helpPages[helpPage]; ok {
98                         CurView().openHelp(helpPage)
99                 } else {
100                         messenger.Error("Sorry, no help for ", helpPage)
101                 }
102         }
103 }
104
105 // VSplit opens a vertical split with file given in the first argument
106 // If no file is given, it opens an empty buffer in a new split
107 func VSplit(args []string) {
108         if len(args) == 0 {
109                 CurView().VSplit(NewBuffer([]byte{}, ""))
110         } else {
111                 filename := args[0]
112                 home, _ := homedir.Dir()
113                 filename = strings.Replace(filename, "~", home, 1)
114                 file, err := ioutil.ReadFile(filename)
115
116                 var buf *Buffer
117                 if err != nil {
118                         // File does not exist -- create an empty buffer with that name
119                         buf = NewBuffer([]byte{}, filename)
120                 } else {
121                         buf = NewBuffer(file, filename)
122                 }
123                 CurView().VSplit(buf)
124         }
125 }
126
127 // HSplit opens a horizontal split with file given in the first argument
128 // If no file is given, it opens an empty buffer in a new split
129 func HSplit(args []string) {
130         if len(args) == 0 {
131                 CurView().HSplit(NewBuffer([]byte{}, ""))
132         } else {
133                 filename := args[0]
134                 home, _ := homedir.Dir()
135                 filename = strings.Replace(filename, "~", home, 1)
136                 file, err := ioutil.ReadFile(filename)
137
138                 var buf *Buffer
139                 if err != nil {
140                         // File does not exist -- create an empty buffer with that name
141                         buf = NewBuffer([]byte{}, filename)
142                 } else {
143                         buf = NewBuffer(file, filename)
144                 }
145                 CurView().HSplit(buf)
146         }
147 }
148
149 // Eval evaluates a lua expression
150 func Eval(args []string) {
151         if len(args) >= 1 {
152                 err := L.DoString(args[0])
153                 if err != nil {
154                         messenger.Error(err)
155                 }
156         } else {
157                 messenger.Error("Not enough arguments")
158         }
159 }
160
161 // NewTab opens the given file in a new tab
162 func NewTab(args []string) {
163         if len(args) == 0 {
164                 CurView().AddTab(true)
165         } else {
166                 filename := args[0]
167                 home, _ := homedir.Dir()
168                 filename = strings.Replace(filename, "~", home, 1)
169                 file, _ := ioutil.ReadFile(filename)
170
171                 tab := NewTabFromView(NewView(NewBuffer(file, filename)))
172                 tab.SetNum(len(tabs))
173                 tabs = append(tabs, tab)
174                 curTab++
175                 if len(tabs) == 2 {
176                         for _, t := range tabs {
177                                 for _, v := range t.views {
178                                         v.ToggleTabbar()
179                                 }
180                         }
181                 }
182         }
183 }
184
185 // Set sets an option
186 func Set(args []string) {
187         if len(args) < 2 {
188                 messenger.Error("Not enough arguments")
189                 return
190         }
191
192         option := strings.TrimSpace(args[0])
193         value := strings.TrimSpace(args[1])
194
195         SetOptionAndSettings(option, value)
196 }
197
198 // SetLocal sets an option local to the buffer
199 func SetLocal(args []string) {
200         if len(args) < 2 {
201                 messenger.Error("Not enough arguments")
202                 return
203         }
204
205         option := strings.TrimSpace(args[0])
206         value := strings.TrimSpace(args[1])
207
208         err := SetLocalOption(option, value, CurView())
209         if err != nil {
210                 messenger.Error(err.Error())
211         }
212 }
213
214 // Show shows the value of the given option
215 func Show(args []string) {
216         if len(args) < 1 {
217                 messenger.Error("Please provide an option to show")
218                 return
219         }
220
221         option := GetOption(args[0])
222
223         if option == nil {
224                 messenger.Error(args[0], " is not a valid option")
225                 return
226         }
227
228         messenger.Message(option)
229 }
230
231 // Bind creates a new keybinding
232 func Bind(args []string) {
233         if len(args) < 2 {
234                 messenger.Error("Not enough arguments")
235                 return
236         }
237         BindKey(args[0], args[1])
238 }
239
240 // Run runs a shell command in the background
241 func Run(args []string) {
242         // Run a shell command in the background (openTerm is false)
243         HandleShellCommand(JoinCommandArgs(args...), false, true)
244 }
245
246 // Quit closes the main view
247 func Quit(args []string) {
248         // Close the main view
249         CurView().Quit(true)
250 }
251
252 // Save saves the buffer in the main view
253 func Save(args []string) {
254         if len(args) == 0 {
255                 // Save the main view
256                 CurView().Save(true)
257         } else {
258                 CurView().Buf.SaveAs(args[0])
259         }
260 }
261
262 // Replace runs search and replace
263 func Replace(args []string) {
264         if len(args) < 2 {
265                 // We need to find both a search and replace expression
266                 messenger.Error("Invalid replace statement: " + strings.Join(args, " "))
267                 return
268         }
269
270         var flags string
271         if len(args) == 3 {
272                 // The user included some flags
273                 flags = args[2]
274         }
275
276         search := string(args[0])
277         replace := string(args[1])
278
279         regex, err := regexp.Compile(search)
280         if err != nil {
281                 // There was an error with the user's regex
282                 messenger.Error(err.Error())
283                 return
284         }
285
286         view := CurView()
287
288         found := 0
289         if strings.Contains(flags, "c") {
290                 for {
291                         // The 'check' flag was used
292                         Search(search, view, true)
293                         if !view.Cursor.HasSelection() {
294                                 break
295                         }
296                         view.Relocate()
297                         if view.Buf.Settings["syntax"].(bool) {
298                                 view.matches = Match(view)
299                         }
300                         RedrawAll()
301                         choice, canceled := messenger.YesNoPrompt("Perform replacement? (y,n)")
302                         if canceled {
303                                 if view.Cursor.HasSelection() {
304                                         view.Cursor.Loc = view.Cursor.CurSelection[0]
305                                         view.Cursor.ResetSelection()
306                                 }
307                                 messenger.Reset()
308                                 break
309                         }
310                         if choice {
311                                 view.Cursor.DeleteSelection()
312                                 view.Buf.Insert(view.Cursor.Loc, replace)
313                                 view.Cursor.ResetSelection()
314                                 messenger.Reset()
315                                 found++
316                         } else {
317                                 if view.Cursor.HasSelection() {
318                                         searchStart = ToCharPos(view.Cursor.CurSelection[1], view.Buf)
319                                 } else {
320                                         searchStart = ToCharPos(view.Cursor.Loc, view.Buf)
321                                 }
322                                 continue
323                         }
324                 }
325         } else {
326                 matches := regex.FindAllStringIndex(view.Buf.String(), -1)
327                 if matches != nil && len(matches) > 0 {
328                         adjust := 0
329                         prevMatch := matches[0]
330                         from := FromCharPos(prevMatch[0], view.Buf)
331                         to := from.Move(Count(search), view.Buf)
332                         adjust += Count(replace) - Count(search)
333                         view.Buf.Replace(from, to, replace)
334                         if len(matches) > 1 {
335                                 for _, match := range matches[1:] {
336                                         found++
337                                         from = from.Move(match[0]-prevMatch[0]+adjust, view.Buf)
338                                         to := from.Move(Count(search), view.Buf)
339                                         // TermMessage(match[0], " ", prevMatch[0], " ", adjust, "\n", from, " ", to)
340                                         view.Buf.Replace(from, to, replace)
341                                         prevMatch = match
342                                         // adjust += Count(replace) - Count(search)
343                                 }
344                         }
345                 }
346         }
347         view.Cursor.Relocate()
348
349         if found > 1 {
350                 messenger.Message("Replaced ", found, " occurrences of ", search)
351         } else if found == 1 {
352                 messenger.Message("Replaced ", found, " occurrence of ", search)
353         } else {
354                 messenger.Message("Nothing matched ", search)
355         }
356 }
357
358 // RunShellCommand executes a shell command and returns the output/error
359 func RunShellCommand(input string) (string, error) {
360         inputCmd := SplitCommandArgs(input)[0]
361         args := SplitCommandArgs(input)[1:]
362
363         cmd := exec.Command(inputCmd, args...)
364         outputBytes := &bytes.Buffer{}
365         cmd.Stdout = outputBytes
366         cmd.Stderr = outputBytes
367         cmd.Start()
368         err := cmd.Wait() // wait for command to finish
369         outstring := outputBytes.String()
370         return outstring, err
371 }
372
373 // HandleShellCommand runs the shell command
374 // The openTerm argument specifies whether a terminal should be opened (for viewing output
375 // or interacting with stdin)
376 func HandleShellCommand(input string, openTerm bool, waitToFinish bool) string {
377         inputCmd := SplitCommandArgs(input)[0]
378         if !openTerm {
379                 // Simply run the command in the background and notify the user when it's done
380                 messenger.Message("Running...")
381                 go func() {
382                         output, err := RunShellCommand(input)
383                         totalLines := strings.Split(output, "\n")
384
385                         if len(totalLines) < 3 {
386                                 if err == nil {
387                                         messenger.Message(inputCmd, " exited without error")
388                                 } else {
389                                         messenger.Message(inputCmd, " exited with error: ", err, ": ", output)
390                                 }
391                         } else {
392                                 messenger.Message(output)
393                         }
394                         // We have to make sure to redraw
395                         RedrawAll()
396                 }()
397         } else {
398                 // Shut down the screen because we're going to interact directly with the shell
399                 screen.Fini()
400                 screen = nil
401
402                 args := SplitCommandArgs(input)[1:]
403
404                 // Set up everything for the command
405                 var outputBuf bytes.Buffer
406                 cmd := exec.Command(inputCmd, args...)
407                 cmd.Stdin = os.Stdin
408                 cmd.Stdout = io.MultiWriter(os.Stdout, &outputBuf)
409                 cmd.Stderr = os.Stderr
410
411                 // This is a trap for Ctrl-C so that it doesn't kill micro
412                 // Instead we trap Ctrl-C to kill the program we're running
413                 c := make(chan os.Signal, 1)
414                 signal.Notify(c, os.Interrupt)
415                 go func() {
416                         for range c {
417                                 cmd.Process.Kill()
418                         }
419                 }()
420
421                 cmd.Start()
422                 err := cmd.Wait()
423
424                 output := outputBuf.String()
425                 if err != nil {
426                         output = err.Error()
427                 }
428
429                 if waitToFinish {
430                         // This is just so we don't return right away and let the user press enter to return
431                         TermMessage("")
432                 }
433
434                 // Start the screen back up
435                 InitScreen()
436
437                 return output
438         }
439         return ""
440 }
441
442 // HandleCommand handles input from the user
443 func HandleCommand(input string) {
444         args := SplitCommandArgs(input)
445         inputCmd := args[0]
446
447         if _, ok := commands[inputCmd]; !ok {
448                 messenger.Error("Unknown command ", inputCmd)
449         } else {
450                 commands[inputCmd].action(args[1:])
451         }
452 }