]> git.lizzy.rs Git - micro.git/blob - cmd/micro/messenger.go
Improve command bar completion
[micro.git] / cmd / micro / messenger.go
1 package main
2
3 import (
4         "bufio"
5         "bytes"
6         "encoding/gob"
7         "fmt"
8         "os"
9         "strconv"
10
11         "github.com/mattn/go-runewidth"
12         "github.com/zyedidia/clipboard"
13         "github.com/zyedidia/micro/cmd/micro/shellwords"
14         "github.com/zyedidia/tcell"
15 )
16
17 // TermMessage sends a message to the user in the terminal. This usually occurs before
18 // micro has been fully initialized -- ie if there is an error in the syntax highlighting
19 // regular expressions
20 // The function must be called when the screen is not initialized
21 // This will write the message, and wait for the user
22 // to press and key to continue
23 func TermMessage(msg ...interface{}) {
24         screenWasNil := screen == nil
25         if !screenWasNil {
26                 screen.Fini()
27                 screen = nil
28         }
29
30         fmt.Println(msg...)
31         fmt.Print("\nPress enter to continue")
32
33         reader := bufio.NewReader(os.Stdin)
34         reader.ReadString('\n')
35
36         if !screenWasNil {
37                 InitScreen()
38         }
39 }
40
41 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
42 // as an error
43 func TermError(filename string, lineNum int, err string) {
44         TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
45 }
46
47 // Messenger is an object that makes it easy to send messages to the user
48 // and get input from the user
49 type Messenger struct {
50         log *Buffer
51         // Are we currently prompting the user?
52         hasPrompt bool
53         // Is there a message to print
54         hasMessage bool
55
56         // Message to print
57         message string
58         // The user's response to a prompt
59         response string
60         // style to use when drawing the message
61         style tcell.Style
62
63         // We have to keep track of the cursor for prompting
64         cursorx int
65
66         // This map stores the history for all the different kinds of uses Prompt has
67         // It's a map of history type -> history array
68         history    map[string][]string
69         historyNum int
70
71         // Is the current message a message from the gutter
72         gutterMessage bool
73 }
74
75 // AddLog sends a message to the log view
76 func (m *Messenger) AddLog(msg ...interface{}) {
77         logMessage := fmt.Sprint(msg...)
78         buffer := m.getBuffer()
79         buffer.insert(buffer.End(), []byte(logMessage+"\n"))
80         buffer.Cursor.Loc = buffer.End()
81         buffer.Cursor.Relocate()
82 }
83
84 func (m *Messenger) getBuffer() *Buffer {
85         if m.log == nil {
86                 m.log = NewBufferFromString("", "")
87                 m.log.name = "Log"
88         }
89         return m.log
90 }
91
92 // Message sends a message to the user
93 func (m *Messenger) Message(msg ...interface{}) {
94         displayMessage := fmt.Sprint(msg...)
95         // only display a new message if there isn't an active prompt
96         // this is to prevent overwriting an existing prompt to the user
97         if m.hasPrompt == false {
98                 // if there is no active prompt then style and display the message as normal
99                 m.message = displayMessage
100
101                 m.style = defStyle
102
103                 if _, ok := colorscheme["message"]; ok {
104                         m.style = colorscheme["message"]
105                 }
106
107                 m.hasMessage = true
108         }
109         // add the message to the log regardless of active prompts
110         m.AddLog(displayMessage)
111 }
112
113 // Error sends an error message to the user
114 func (m *Messenger) Error(msg ...interface{}) {
115         buf := new(bytes.Buffer)
116         fmt.Fprint(buf, msg...)
117
118         // only display a new message if there isn't an active prompt
119         // this is to prevent overwriting an existing prompt to the user
120         if m.hasPrompt == false {
121                 // if there is no active prompt then style and display the message as normal
122                 m.message = buf.String()
123                 m.style = defStyle.
124                         Foreground(tcell.ColorBlack).
125                         Background(tcell.ColorMaroon)
126
127                 if _, ok := colorscheme["error-message"]; ok {
128                         m.style = colorscheme["error-message"]
129                 }
130                 m.hasMessage = true
131         }
132         // add the message to the log regardless of active prompts
133         m.AddLog(buf.String())
134 }
135
136 func (m *Messenger) PromptText(msg ...interface{}) {
137         displayMessage := fmt.Sprint(msg...)
138         // if there is no active prompt then style and display the message as normal
139         m.message = displayMessage
140
141         m.style = defStyle
142
143         if _, ok := colorscheme["message"]; ok {
144                 m.style = colorscheme["message"]
145         }
146
147         m.hasMessage = true
148         // add the message to the log regardless of active prompts
149         m.AddLog(displayMessage)
150 }
151
152 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
153 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
154         m.hasPrompt = true
155         m.PromptText(prompt)
156
157         _, h := screen.Size()
158         for {
159                 m.Clear()
160                 m.Display()
161                 screen.ShowCursor(Count(m.message), h-1)
162                 screen.Show()
163                 event := <-events
164
165                 switch e := event.(type) {
166                 case *tcell.EventKey:
167                         switch e.Key() {
168                         case tcell.KeyRune:
169                                 if e.Rune() == 'y' || e.Rune() == 'Y' {
170                                         m.AddLog("\t--> y")
171                                         m.hasPrompt = false
172                                         return true, false
173                                 } else if e.Rune() == 'n' || e.Rune() == 'N' {
174                                         m.AddLog("\t--> n")
175                                         m.hasPrompt = false
176                                         return false, false
177                                 }
178                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
179                                 m.AddLog("\t--> (cancel)")
180                                 m.Clear()
181                                 m.Reset()
182                                 m.hasPrompt = false
183                                 return false, true
184                         }
185                 }
186         }
187 }
188
189 // LetterPrompt gives the user a prompt and waits for a one letter response
190 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
191         m.hasPrompt = true
192         m.PromptText(prompt)
193
194         _, h := screen.Size()
195         for {
196                 m.Clear()
197                 m.Display()
198                 screen.ShowCursor(Count(m.message), h-1)
199                 screen.Show()
200                 event := <-events
201
202                 switch e := event.(type) {
203                 case *tcell.EventKey:
204                         switch e.Key() {
205                         case tcell.KeyRune:
206                                 for _, r := range responses {
207                                         if e.Rune() == r {
208                                                 m.AddLog("\t--> " + string(r))
209                                                 m.Clear()
210                                                 m.Reset()
211                                                 m.hasPrompt = false
212                                                 return r, false
213                                         }
214                                 }
215                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
216                                 m.AddLog("\t--> (cancel)")
217                                 m.Clear()
218                                 m.Reset()
219                                 m.hasPrompt = false
220                                 return ' ', true
221                         }
222                 }
223         }
224 }
225
226 type Completion int
227
228 const (
229         NoCompletion Completion = iota
230         FileCompletion
231         CommandCompletion
232         HelpCompletion
233         OptionCompletion
234         PluginCmdCompletion
235         PluginNameCompletion
236         OptionValueCompletion
237 )
238
239 // Prompt sends the user a message and waits for a response to be typed in
240 // This function blocks the main loop while waiting for input
241 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
242         m.hasPrompt = true
243         m.PromptText(prompt)
244         if _, ok := m.history[historyType]; !ok {
245                 m.history[historyType] = []string{""}
246         } else {
247                 m.history[historyType] = append(m.history[historyType], "")
248         }
249         m.historyNum = len(m.history[historyType]) - 1
250
251         response, canceled := placeholder, true
252         m.response = response
253         m.cursorx = Count(placeholder)
254
255         RedrawAll()
256         for m.hasPrompt {
257                 var suggestions []string
258                 m.Clear()
259
260                 event := <-events
261
262                 switch e := event.(type) {
263                 case *tcell.EventKey:
264                         switch e.Key() {
265                         case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
266                                 // Cancel
267                                 m.AddLog("\t--> (cancel)")
268                                 m.hasPrompt = false
269                         case tcell.KeyEnter:
270                                 // User is done entering their response
271                                 m.AddLog("\t--> " + m.response)
272                                 m.hasPrompt = false
273                                 response, canceled = m.response, false
274                                 m.history[historyType][len(m.history[historyType])-1] = response
275                         case tcell.KeyTab:
276                                 args, err := shellwords.Split(m.response)
277                                 if err != nil {
278                                         break
279                                 }
280                                 currentArg := ""
281                                 currentArgNum := 0
282                                 if len(args) > 0 {
283                                         currentArgNum = len(args) - 1
284                                         currentArg = args[currentArgNum]
285                                 }
286                                 var completionType Completion
287
288                                 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
289                                         if command, ok := commands[args[0]]; ok {
290                                                 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
291                                         }
292                                 }
293
294                                 if currentArgNum >= len(completionTypes) {
295                                         completionType = completionTypes[len(completionTypes)-1]
296                                 } else {
297                                         completionType = completionTypes[currentArgNum]
298                                 }
299
300                                 var chosen string
301                                 if completionType == FileCompletion {
302                                         chosen, suggestions = FileComplete(currentArg)
303                                 } else if completionType == CommandCompletion {
304                                         chosen, suggestions = CommandComplete(currentArg)
305                                 } else if completionType == HelpCompletion {
306                                         chosen, suggestions = HelpComplete(currentArg)
307                                 } else if completionType == OptionCompletion {
308                                         chosen, suggestions = OptionComplete(currentArg)
309                                 } else if completionType == OptionValueCompletion {
310                                         if currentArgNum-1 > 0 {
311                                                 chosen, suggestions = OptionValueComplete(args[currentArgNum-1], currentArg)
312                                         }
313                                 } else if completionType == PluginCmdCompletion {
314                                         chosen, suggestions = PluginCmdComplete(currentArg)
315                                 } else if completionType == PluginNameCompletion {
316                                         chosen, suggestions = PluginNameComplete(currentArg)
317                                 } else if completionType < NoCompletion {
318                                         chosen, suggestions = PluginComplete(completionType, currentArg)
319                                 }
320
321                                 if len(suggestions) > 1 {
322                                         chosen = chosen + CommonSubstring(suggestions...)
323                                 }
324
325                                 if len(suggestions) != 0 {
326                                         m.response = shellwords.Join(append(args[:len(args)-1], chosen)...)
327                                         m.cursorx = Count(m.response)
328                                 }
329                         }
330                 }
331
332                 m.HandleEvent(event, m.history[historyType])
333
334                 m.Clear()
335                 for _, v := range tabs[curTab].views {
336                         v.Display()
337                 }
338                 DisplayTabs()
339                 m.Display()
340                 if len(suggestions) > 1 {
341                         m.DisplaySuggestions(suggestions)
342                 }
343                 screen.Show()
344         }
345
346         m.Clear()
347         m.Reset()
348         return response, canceled
349 }
350
351 func (m *Messenger) UpHistory(history []string) {
352         if m.historyNum > 0 {
353                 m.historyNum--
354                 m.response = history[m.historyNum]
355                 m.cursorx = Count(m.response)
356         }
357 }
358 func (m *Messenger) DownHistory(history []string) {
359         if m.historyNum < len(history)-1 {
360                 m.historyNum++
361                 m.response = history[m.historyNum]
362                 m.cursorx = Count(m.response)
363         }
364 }
365 func (m *Messenger) CursorLeft() {
366         if m.cursorx > 0 {
367                 m.cursorx--
368         }
369 }
370 func (m *Messenger) CursorRight() {
371         if m.cursorx < Count(m.response) {
372                 m.cursorx++
373         }
374 }
375 func (m *Messenger) Start() {
376         m.cursorx = 0
377 }
378 func (m *Messenger) End() {
379         m.cursorx = Count(m.response)
380 }
381 func (m *Messenger) Backspace() {
382         if m.cursorx > 0 {
383                 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
384                 m.cursorx--
385         }
386 }
387 func (m *Messenger) Paste() {
388         clip, _ := clipboard.ReadAll("clipboard")
389         m.response = Insert(m.response, m.cursorx, clip)
390         m.cursorx += Count(clip)
391 }
392 func (m *Messenger) WordLeft() {
393         response := []rune(m.response)
394         m.CursorLeft()
395         if m.cursorx <= 0 {
396                 return
397         }
398         for IsWhitespace(response[m.cursorx]) {
399                 if m.cursorx <= 0 {
400                         return
401                 }
402                 m.CursorLeft()
403         }
404         m.CursorLeft()
405         for IsWordChar(string(response[m.cursorx])) {
406                 if m.cursorx <= 0 {
407                         return
408                 }
409                 m.CursorLeft()
410         }
411         m.CursorRight()
412 }
413 func (m *Messenger) WordRight() {
414         response := []rune(m.response)
415         if m.cursorx >= len(response) {
416                 return
417         }
418         for IsWhitespace(response[m.cursorx]) {
419                 m.CursorRight()
420                 if m.cursorx >= len(response) {
421                         m.CursorRight()
422                         return
423                 }
424         }
425         m.CursorRight()
426         if m.cursorx >= len(response) {
427                 return
428         }
429         for IsWordChar(string(response[m.cursorx])) {
430                 m.CursorRight()
431                 if m.cursorx >= len(response) {
432                         return
433                 }
434         }
435 }
436 func (m *Messenger) DeleteWordLeft() {
437         m.WordLeft()
438         m.response = string([]rune(m.response)[:m.cursorx])
439 }
440
441 // HandleEvent handles an event for the prompter
442 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
443         switch e := event.(type) {
444         case *tcell.EventKey:
445                 switch e.Key() {
446                 case tcell.KeyCtrlA:
447                         m.Start()
448                 case tcell.KeyCtrlE:
449                         m.End()
450                 case tcell.KeyUp:
451                         m.UpHistory(history)
452                 case tcell.KeyDown:
453                         m.DownHistory(history)
454                 case tcell.KeyLeft:
455                         if e.Modifiers() == tcell.ModCtrl {
456                                 m.Start()
457                         } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
458                                 m.WordLeft()
459                         } else {
460                                 m.CursorLeft()
461                         }
462                 case tcell.KeyRight:
463                         if e.Modifiers() == tcell.ModCtrl {
464                                 m.End()
465                         } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
466                                 m.WordRight()
467                         } else {
468                                 m.CursorRight()
469                         }
470                 case tcell.KeyBackspace2, tcell.KeyBackspace:
471                         if e.Modifiers() == tcell.ModCtrl || e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
472                                 m.DeleteWordLeft()
473                         } else {
474                                 m.Backspace()
475                         }
476                 case tcell.KeyCtrlW:
477                         m.DeleteWordLeft()
478                 case tcell.KeyCtrlV:
479                         m.Paste()
480                 case tcell.KeyCtrlF:
481                         m.WordRight()
482                 case tcell.KeyCtrlB:
483                         m.WordLeft()
484                 case tcell.KeyRune:
485                         m.response = Insert(m.response, m.cursorx, string(e.Rune()))
486                         m.cursorx++
487                 }
488                 history[m.historyNum] = m.response
489
490         case *tcell.EventPaste:
491                 clip := e.Text()
492                 m.response = Insert(m.response, m.cursorx, clip)
493                 m.cursorx += Count(clip)
494         case *tcell.EventMouse:
495                 x, y := e.Position()
496                 x -= Count(m.message)
497                 button := e.Buttons()
498                 _, screenH := screen.Size()
499
500                 if y == screenH-1 {
501                         switch button {
502                         case tcell.Button1:
503                                 m.cursorx = x
504                                 if m.cursorx < 0 {
505                                         m.cursorx = 0
506                                 } else if m.cursorx > Count(m.response) {
507                                         m.cursorx = Count(m.response)
508                                 }
509                         }
510                 }
511         }
512 }
513
514 // Reset resets the messenger's cursor, message and response
515 func (m *Messenger) Reset() {
516         m.cursorx = 0
517         m.message = ""
518         m.response = ""
519 }
520
521 // Clear clears the line at the bottom of the editor
522 func (m *Messenger) Clear() {
523         w, h := screen.Size()
524         for x := 0; x < w; x++ {
525                 screen.SetContent(x, h-1, ' ', nil, defStyle)
526         }
527 }
528
529 func (m *Messenger) DisplaySuggestions(suggestions []string) {
530         w, screenH := screen.Size()
531
532         y := screenH - 2
533
534         statusLineStyle := defStyle.Reverse(true)
535         if style, ok := colorscheme["statusline"]; ok {
536                 statusLineStyle = style
537         }
538
539         for x := 0; x < w; x++ {
540                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
541         }
542
543         x := 0
544         for _, suggestion := range suggestions {
545                 for _, c := range suggestion {
546                         screen.SetContent(x, y, c, nil, statusLineStyle)
547                         x++
548                 }
549                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
550                 x++
551         }
552 }
553
554 // Display displays messages or prompts
555 func (m *Messenger) Display() {
556         _, h := screen.Size()
557         if m.hasMessage {
558                 if m.hasPrompt || globalSettings["infobar"].(bool) {
559                         runes := []rune(m.message + m.response)
560                         posx := 0
561                         for x := 0; x < len(runes); x++ {
562                                 screen.SetContent(posx, h-1, runes[x], nil, m.style)
563                                 posx += runewidth.RuneWidth(runes[x])
564                         }
565                 }
566         }
567
568         if m.hasPrompt {
569                 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
570                 screen.Show()
571         }
572 }
573
574 // LoadHistory attempts to load user history from configDir/buffers/history
575 // into the history map
576 // The savehistory option must be on
577 func (m *Messenger) LoadHistory() {
578         if GetGlobalOption("savehistory").(bool) {
579                 file, err := os.Open(configDir + "/buffers/history")
580                 var decodedMap map[string][]string
581                 if err == nil {
582                         decoder := gob.NewDecoder(file)
583                         err = decoder.Decode(&decodedMap)
584                         file.Close()
585
586                         if err != nil {
587                                 m.Error("Error loading history:", err)
588                                 return
589                         }
590                 }
591
592                 if decodedMap != nil {
593                         m.history = decodedMap
594                 } else {
595                         m.history = make(map[string][]string)
596                 }
597         } else {
598                 m.history = make(map[string][]string)
599         }
600 }
601
602 // SaveHistory saves the user's command history to configDir/buffers/history
603 // only if the savehistory option is on
604 func (m *Messenger) SaveHistory() {
605         if GetGlobalOption("savehistory").(bool) {
606                 // Don't save history past 100
607                 for k, v := range m.history {
608                         if len(v) > 100 {
609                                 m.history[k] = v[len(m.history[k])-100:]
610                         }
611                 }
612
613                 file, err := os.Create(configDir + "/buffers/history")
614                 if err == nil {
615                         encoder := gob.NewEncoder(file)
616
617                         err = encoder.Encode(m.history)
618                         if err != nil {
619                                 m.Error("Error saving history:", err)
620                                 return
621                         }
622                         file.Close()
623                 }
624         }
625 }
626
627 // A GutterMessage is a message displayed on the side of the editor
628 type GutterMessage struct {
629         lineNum int
630         msg     string
631         kind    int
632 }
633
634 // These are the different types of messages
635 const (
636         // GutterInfo represents a simple info message
637         GutterInfo = iota
638         // GutterWarning represents a compiler warning
639         GutterWarning
640         // GutterError represents a compiler error
641         GutterError
642 )