]> git.lizzy.rs Git - micro.git/blob - cmd/micro/messenger.go
f032741ac0d86a8318bd097095f7a211ff17081b
[micro.git] / cmd / micro / messenger.go
1 package main
2
3 import (
4         "bufio"
5         "bytes"
6         "fmt"
7         "os"
8         "strconv"
9
10         "github.com/zyedidia/clipboard"
11         "github.com/zyedidia/tcell"
12 )
13
14 // TermMessage sends a message to the user in the terminal. This usually occurs before
15 // micro has been fully initialized -- ie if there is an error in the syntax highlighting
16 // regular expressions
17 // The function must be called when the screen is not initialized
18 // This will write the message, and wait for the user
19 // to press and key to continue
20 func TermMessage(msg ...interface{}) {
21         screenWasNil := screen == nil
22         if !screenWasNil {
23                 screen.Fini()
24                 screen = nil
25         }
26
27         fmt.Println(msg...)
28         fmt.Print("\nPress enter to continue")
29
30         reader := bufio.NewReader(os.Stdin)
31         reader.ReadString('\n')
32
33         if !screenWasNil {
34                 InitScreen()
35         }
36 }
37
38 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
39 // as an error
40 func TermError(filename string, lineNum int, err string) {
41         TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
42 }
43
44 // Messenger is an object that makes it easy to send messages to the user
45 // and get input from the user
46 type Messenger struct {
47         log *Buffer
48         // Are we currently prompting the user?
49         hasPrompt bool
50         // Is there a message to print
51         hasMessage bool
52
53         // Message to print
54         message string
55         // The user's response to a prompt
56         response string
57         // style to use when drawing the message
58         style tcell.Style
59
60         // We have to keep track of the cursor for prompting
61         cursorx int
62
63         // This map stores the history for all the different kinds of uses Prompt has
64         // It's a map of history type -> history array
65         history    map[string][]string
66         historyNum int
67
68         // Is the current message a message from the gutter
69         gutterMessage bool
70 }
71
72 func (m *Messenger) AddLog(msg string) {
73         buffer := m.getBuffer()
74         buffer.insert(buffer.End(), []byte(msg+"\n"))
75         buffer.Cursor.Loc = buffer.End()
76         buffer.Cursor.Relocate()
77 }
78
79 func (m *Messenger) getBuffer() *Buffer {
80         if m.log == nil {
81                 m.log = NewBufferFromString("", "")
82                 m.log.name = "Log"
83         }
84         return m.log
85 }
86
87 // Message sends a message to the user
88 func (m *Messenger) Message(msg ...interface{}) {
89         displayMessage := fmt.Sprint(msg...)
90         // only display a new message if there isn't an active prompt
91         // this is to prevent overwriting an existing prompt to the user
92         if m.hasPrompt == false {
93                 // if there is no active prompt then style and display the message as normal
94                 m.message = displayMessage
95
96                 m.style = defStyle
97
98                 if _, ok := colorscheme["message"]; ok {
99                         m.style = colorscheme["message"]
100                 }
101
102                 m.hasMessage = true
103         }
104         // add the message to the log regardless of active prompts
105         m.AddLog(displayMessage)
106 }
107
108 // Error sends an error message to the user
109 func (m *Messenger) Error(msg ...interface{}) {
110         buf := new(bytes.Buffer)
111         fmt.Fprint(buf, msg...)
112
113         // only display a new message if there isn't an active prompt
114         // this is to prevent overwriting an existing prompt to the user
115         if m.hasPrompt == false {
116                 // if there is no active prompt then style and display the message as normal
117                 m.message = buf.String()
118                 m.style = defStyle.
119                         Foreground(tcell.ColorBlack).
120                         Background(tcell.ColorMaroon)
121
122                 if _, ok := colorscheme["error-message"]; ok {
123                         m.style = colorscheme["error-message"]
124                 }
125                 m.hasMessage = true
126         }
127         // add the message to the log regardless of active prompts
128         m.AddLog(buf.String())
129 }
130
131 func (m *Messenger) PromptText(msg ...interface{}) {
132         displayMessage := fmt.Sprint(msg...)
133         // if there is no active prompt then style and display the message as normal
134         m.message = displayMessage
135
136         m.style = defStyle
137
138         if _, ok := colorscheme["message"]; ok {
139                 m.style = colorscheme["message"]
140         }
141
142         m.hasMessage = true
143         // add the message to the log regardless of active prompts
144         m.AddLog(displayMessage)
145 }
146
147 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
148 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
149         m.hasPrompt = true
150         m.PromptText(prompt)
151
152         _, h := screen.Size()
153         for {
154                 m.Clear()
155                 m.Display()
156                 screen.ShowCursor(Count(m.message), h-1)
157                 screen.Show()
158                 event := <-events
159
160                 switch e := event.(type) {
161                 case *tcell.EventKey:
162                         switch e.Key() {
163                         case tcell.KeyRune:
164                                 if e.Rune() == 'y' {
165                                         m.AddLog("\t--> y")
166                                         m.hasPrompt = false
167                                         return true, false
168                                 } else if e.Rune() == 'n' {
169                                         m.AddLog("\t--> n")
170                                         m.hasPrompt = false
171                                         return false, false
172                                 }
173                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
174                                 m.AddLog("\t--> (cancel)")
175                                 m.hasPrompt = false
176                                 return false, true
177                         }
178                 }
179         }
180 }
181
182 // LetterPrompt gives the user a prompt and waits for a one letter response
183 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
184         m.hasPrompt = true
185         m.PromptText(prompt)
186
187         _, h := screen.Size()
188         for {
189                 m.Clear()
190                 m.Display()
191                 screen.ShowCursor(Count(m.message), h-1)
192                 screen.Show()
193                 event := <-events
194
195                 switch e := event.(type) {
196                 case *tcell.EventKey:
197                         switch e.Key() {
198                         case tcell.KeyRune:
199                                 for _, r := range responses {
200                                         if e.Rune() == r {
201                                                 m.AddLog("\t--> " + string(r))
202                                                 m.Clear()
203                                                 m.Reset()
204                                                 m.hasPrompt = false
205                                                 return r, false
206                                         }
207                                 }
208                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
209                                 m.AddLog("\t--> (cancel)")
210                                 m.Clear()
211                                 m.Reset()
212                                 m.hasPrompt = false
213                                 return ' ', true
214                         }
215                 }
216         }
217 }
218
219 type Completion int
220
221 const (
222         NoCompletion Completion = iota
223         FileCompletion
224         CommandCompletion
225         HelpCompletion
226         OptionCompletion
227         PluginCmdCompletion
228         PluginNameCompletion
229 )
230
231 // Prompt sends the user a message and waits for a response to be typed in
232 // This function blocks the main loop while waiting for input
233 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
234         m.hasPrompt = true
235         m.PromptText(prompt)
236         if _, ok := m.history[historyType]; !ok {
237                 m.history[historyType] = []string{""}
238         } else {
239                 m.history[historyType] = append(m.history[historyType], "")
240         }
241         m.historyNum = len(m.history[historyType]) - 1
242
243         response, canceled := placeholder, true
244         m.response = response
245         m.cursorx = Count(placeholder)
246
247         RedrawAll()
248         for m.hasPrompt {
249                 var suggestions []string
250                 m.Clear()
251
252                 event := <-events
253
254                 switch e := event.(type) {
255                 case *tcell.EventKey:
256                         switch e.Key() {
257                         case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
258                                 // Cancel
259                                 m.AddLog("\t--> (cancel)")
260                                 m.hasPrompt = false
261                         case tcell.KeyEnter:
262                                 // User is done entering their response
263                                 m.AddLog("\t--> " + m.response)
264                                 m.hasPrompt = false
265                                 response, canceled = m.response, false
266                                 m.history[historyType][len(m.history[historyType])-1] = response
267                         case tcell.KeyTab:
268                                 args := SplitCommandArgs(m.response)
269                                 currentArgNum := len(args) - 1
270                                 currentArg := args[currentArgNum]
271                                 var completionType Completion
272
273                                 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
274                                         if command, ok := commands[args[0]]; ok {
275                                                 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
276                                         }
277                                 }
278
279                                 if currentArgNum >= len(completionTypes) {
280                                         completionType = completionTypes[len(completionTypes)-1]
281                                 } else {
282                                         completionType = completionTypes[currentArgNum]
283                                 }
284
285                                 var chosen string
286                                 if completionType == FileCompletion {
287                                         chosen, suggestions = FileComplete(currentArg)
288                                 } else if completionType == CommandCompletion {
289                                         chosen, suggestions = CommandComplete(currentArg)
290                                 } else if completionType == HelpCompletion {
291                                         chosen, suggestions = HelpComplete(currentArg)
292                                 } else if completionType == OptionCompletion {
293                                         chosen, suggestions = OptionComplete(currentArg)
294                                 } else if completionType == PluginCmdCompletion {
295                                         chosen, suggestions = PluginCmdComplete(currentArg)
296                                 } else if completionType == PluginNameCompletion {
297                                         chosen, suggestions = PluginNameComplete(currentArg)
298                                 } else if completionType < NoCompletion {
299                                         chosen, suggestions = PluginComplete(completionType, currentArg)
300                                 }
301
302                                 if len(suggestions) > 1 {
303                                         chosen = chosen + CommonSubstring(suggestions...)
304                                 }
305
306                                 if chosen != "" {
307                                         m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
308                                         m.cursorx = Count(m.response)
309                                 }
310                         }
311                 }
312
313                 m.HandleEvent(event, m.history[historyType])
314
315                 m.Clear()
316                 for _, v := range tabs[curTab].views {
317                         v.Display()
318                 }
319                 DisplayTabs()
320                 m.Display()
321                 if len(suggestions) > 1 {
322                         m.DisplaySuggestions(suggestions)
323                 }
324                 screen.Show()
325         }
326
327         m.Clear()
328         m.Reset()
329         return response, canceled
330 }
331
332 // HandleEvent handles an event for the prompter
333 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
334         switch e := event.(type) {
335         case *tcell.EventKey:
336                 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
337                         for key, actions := range bindings {
338                                 if e.Key() == key.keyCode {
339                                         if e.Key() == tcell.KeyRune {
340                                                 if e.Rune() != key.r {
341                                                         continue
342                                                 }
343                                         }
344                                         if e.Modifiers() == key.modifiers {
345                                                 for _, action := range actions {
346                                                         funcName := FuncName(action)
347                                                         switch funcName {
348                                                         case "main.(*View).CursorUp":
349                                                                 if m.historyNum > 0 {
350                                                                         m.historyNum--
351                                                                         m.response = history[m.historyNum]
352                                                                         m.cursorx = Count(m.response)
353                                                                 }
354                                                         case "main.(*View).CursorDown":
355                                                                 if m.historyNum < len(history)-1 {
356                                                                         m.historyNum++
357                                                                         m.response = history[m.historyNum]
358                                                                         m.cursorx = Count(m.response)
359                                                                 }
360                                                         case "main.(*View).CursorLeft":
361                                                                 if m.cursorx > 0 {
362                                                                         m.cursorx--
363                                                                 }
364                                                         case "main.(*View).CursorRight":
365                                                                 if m.cursorx < Count(m.response) {
366                                                                         m.cursorx++
367                                                                 }
368                                                         case "main.(*View).CursorStart", "main.(*View).StartOfLine":
369                                                                 m.cursorx = 0
370                                                         case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
371                                                                 m.cursorx = Count(m.response)
372                                                         case "main.(*View).Backspace":
373                                                                 if m.cursorx > 0 {
374                                                                         m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
375                                                                         m.cursorx--
376                                                                 }
377                                                         case "main.(*View).Paste":
378                                                                 clip, _ := clipboard.ReadAll("clipboard")
379                                                                 m.response = Insert(m.response, m.cursorx, clip)
380                                                                 m.cursorx += Count(clip)
381                                                         }
382                                                 }
383                                         }
384                                 }
385                         }
386                 }
387                 switch e.Key() {
388                 case tcell.KeyRune:
389                         m.response = Insert(m.response, m.cursorx, string(e.Rune()))
390                         m.cursorx++
391                 }
392                 history[m.historyNum] = m.response
393
394         case *tcell.EventPaste:
395                 clip := e.Text()
396                 m.response = Insert(m.response, m.cursorx, clip)
397                 m.cursorx += Count(clip)
398         case *tcell.EventMouse:
399                 x, y := e.Position()
400                 x -= Count(m.message)
401                 button := e.Buttons()
402                 _, screenH := screen.Size()
403
404                 if y == screenH-1 {
405                         switch button {
406                         case tcell.Button1:
407                                 m.cursorx = x
408                                 if m.cursorx < 0 {
409                                         m.cursorx = 0
410                                 } else if m.cursorx > Count(m.response) {
411                                         m.cursorx = Count(m.response)
412                                 }
413                         }
414                 }
415         }
416 }
417
418 // Reset resets the messenger's cursor, message and response
419 func (m *Messenger) Reset() {
420         m.cursorx = 0
421         m.message = ""
422         m.response = ""
423 }
424
425 // Clear clears the line at the bottom of the editor
426 func (m *Messenger) Clear() {
427         w, h := screen.Size()
428         for x := 0; x < w; x++ {
429                 screen.SetContent(x, h-1, ' ', nil, defStyle)
430         }
431 }
432
433 func (m *Messenger) DisplaySuggestions(suggestions []string) {
434         w, screenH := screen.Size()
435
436         y := screenH - 2
437
438         statusLineStyle := defStyle.Reverse(true)
439         if style, ok := colorscheme["statusline"]; ok {
440                 statusLineStyle = style
441         }
442
443         for x := 0; x < w; x++ {
444                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
445         }
446
447         x := 0
448         for _, suggestion := range suggestions {
449                 for _, c := range suggestion {
450                         screen.SetContent(x, y, c, nil, statusLineStyle)
451                         x++
452                 }
453                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
454                 x++
455         }
456 }
457
458 // Display displays messages or prompts
459 func (m *Messenger) Display() {
460         _, h := screen.Size()
461         if m.hasMessage {
462                 if m.hasPrompt || globalSettings["infobar"].(bool) {
463                         runes := []rune(m.message + m.response)
464                         for x := 0; x < len(runes); x++ {
465                                 screen.SetContent(x, h-1, runes[x], nil, m.style)
466                         }
467                 }
468         }
469
470         if m.hasPrompt {
471                 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
472                 screen.Show()
473         }
474 }
475
476 // A GutterMessage is a message displayed on the side of the editor
477 type GutterMessage struct {
478         lineNum int
479         msg     string
480         kind    int
481 }
482
483 // These are the different types of messages
484 const (
485         // GutterInfo represents a simple info message
486         GutterInfo = iota
487         // GutterWarning represents a compiler warning
488         GutterWarning
489         // GutterError represents a compiler error
490         GutterError
491 )