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