]> git.lizzy.rs Git - micro.git/blob - cmd/micro/messenger.go
Merge pull request #286 from boombuler/bug269
[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         }
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         // Are we currently prompting the user?
48         hasPrompt bool
49         // Is there a message to print
50         hasMessage bool
51
52         // Message to print
53         message string
54         // The user's response to a prompt
55         response string
56         // style to use when drawing the message
57         style tcell.Style
58
59         // We have to keep track of the cursor for prompting
60         cursorx int
61
62         // This map stores the history for all the different kinds of uses Prompt has
63         // It's a map of history type -> history array
64         history    map[string][]string
65         historyNum int
66
67         // Is the current message a message from the gutter
68         gutterMessage bool
69 }
70
71 // Message sends a message to the user
72 func (m *Messenger) Message(msg ...interface{}) {
73         buf := new(bytes.Buffer)
74         fmt.Fprint(buf, msg...)
75         m.message = buf.String()
76         m.style = defStyle
77
78         if _, ok := colorscheme["message"]; ok {
79                 m.style = colorscheme["message"]
80         }
81         m.hasMessage = true
82 }
83
84 // Error sends an error message to the user
85 func (m *Messenger) Error(msg ...interface{}) {
86         buf := new(bytes.Buffer)
87         fmt.Fprint(buf, msg...)
88         m.message = buf.String()
89         m.style = defStyle.
90                 Foreground(tcell.ColorBlack).
91                 Background(tcell.ColorMaroon)
92
93         if _, ok := colorscheme["error-message"]; ok {
94                 m.style = colorscheme["error-message"]
95         }
96         m.hasMessage = true
97 }
98
99 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
100 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
101         m.hasPrompt = true
102         m.Message(prompt)
103
104         _, h := screen.Size()
105         for {
106                 m.Clear()
107                 m.Display()
108                 screen.ShowCursor(Count(m.message), h-1)
109                 screen.Show()
110                 event := <-events
111
112                 switch e := event.(type) {
113                 case *tcell.EventKey:
114                         switch e.Key() {
115                         case tcell.KeyRune:
116                                 if e.Rune() == 'y' {
117                                         return true, false
118                                 } else if e.Rune() == 'n' {
119                                         return false, false
120                                 }
121                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
122                                 return false, true
123                         }
124                 }
125         }
126 }
127
128 // LetterPrompt gives the user a prompt and waits for a one letter response
129 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
130         m.hasPrompt = true
131         m.Message(prompt)
132
133         _, h := screen.Size()
134         for {
135                 m.Clear()
136                 m.Display()
137                 screen.ShowCursor(Count(m.message), h-1)
138                 screen.Show()
139                 event := <-events
140
141                 switch e := event.(type) {
142                 case *tcell.EventKey:
143                         switch e.Key() {
144                         case tcell.KeyRune:
145                                 for _, r := range responses {
146                                         if e.Rune() == r {
147                                                 m.Reset()
148                                                 return r, false
149                                         }
150                                 }
151                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
152                                 return ' ', true
153                         }
154                 }
155         }
156 }
157
158 type Completion int
159
160 const (
161         NoCompletion Completion = iota
162         FileCompletion
163         CommandCompletion
164         HelpCompletion
165         OptionCompletion
166 )
167
168 // Prompt sends the user a message and waits for a response to be typed in
169 // This function blocks the main loop while waiting for input
170 func (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {
171         m.hasPrompt = true
172         m.Message(prompt)
173         if _, ok := m.history[historyType]; !ok {
174                 m.history[historyType] = []string{""}
175         } else {
176                 m.history[historyType] = append(m.history[historyType], "")
177         }
178         m.historyNum = len(m.history[historyType]) - 1
179
180         response, canceled := "", true
181
182         RedrawAll()
183         for m.hasPrompt {
184                 var suggestions []string
185                 m.Clear()
186
187                 event := <-events
188
189                 switch e := event.(type) {
190                 case *tcell.EventKey:
191                         switch e.Key() {
192                         case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
193                                 // Cancel
194                                 m.hasPrompt = false
195                         case tcell.KeyEnter:
196                                 // User is done entering their response
197                                 m.hasPrompt = false
198                                 response, canceled = m.response, false
199                                 m.history[historyType][len(m.history[historyType])-1] = response
200                         case tcell.KeyTab:
201                                 args := strings.Split(m.response, " ")
202                                 currentArgNum := len(args) - 1
203                                 currentArg := args[currentArgNum]
204                                 var completionType Completion
205
206                                 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
207                                         if command, ok := commands[args[0]]; ok {
208                                                 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
209                                         }
210                                 }
211
212                                 if currentArgNum >= len(completionTypes) {
213                                         completionType = completionTypes[len(completionTypes)-1]
214                                 } else {
215                                         completionType = completionTypes[currentArgNum]
216                                 }
217
218                                 var chosen string
219                                 if completionType == FileCompletion {
220                                         chosen, suggestions = FileComplete(currentArg)
221                                 } else if completionType == CommandCompletion {
222                                         chosen, suggestions = CommandComplete(currentArg)
223                                 } else if completionType == HelpCompletion {
224                                         chosen, suggestions = HelpComplete(currentArg)
225                                 } else if completionType == OptionCompletion {
226                                         chosen, suggestions = OptionComplete(currentArg)
227                                 }
228
229                                 if len(suggestions) > 1 {
230                                         chosen = chosen + CommonSubstring(suggestions...)
231                                 }
232
233                                 if chosen != "" {
234                                         if len(args) > 1 {
235                                                 chosen = " " + chosen
236                                         }
237                                         m.response = strings.Join(args[:len(args)-1], " ") + chosen
238                                         m.cursorx = Count(m.response)
239                                 }
240                         }
241                 }
242
243                 m.HandleEvent(event, m.history[historyType])
244
245                 messenger.Clear()
246                 for _, v := range tabs[curTab].views {
247                         v.Display()
248                 }
249                 DisplayTabs()
250                 messenger.Display()
251                 if len(suggestions) > 1 {
252                         m.DisplaySuggestions(suggestions)
253                 }
254                 screen.Show()
255         }
256
257         m.Reset()
258         return response, canceled
259 }
260
261 // HandleEvent handles an event for the prompter
262 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
263         switch e := event.(type) {
264         case *tcell.EventKey:
265                 switch e.Key() {
266                 case tcell.KeyUp:
267                         if m.historyNum > 0 {
268                                 m.historyNum--
269                                 m.response = history[m.historyNum]
270                                 m.cursorx = Count(m.response)
271                         }
272                 case tcell.KeyDown:
273                         if m.historyNum < len(history)-1 {
274                                 m.historyNum++
275                                 m.response = history[m.historyNum]
276                                 m.cursorx = Count(m.response)
277                         }
278                 case tcell.KeyLeft:
279                         if m.cursorx > 0 {
280                                 m.cursorx--
281                         }
282                 case tcell.KeyRight:
283                         if m.cursorx < Count(m.response) {
284                                 m.cursorx++
285                         }
286                 case tcell.KeyBackspace2, tcell.KeyBackspace:
287                         if m.cursorx > 0 {
288                                 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
289                                 m.cursorx--
290                         }
291                 case tcell.KeyCtrlV:
292                         clip, _ := clipboard.ReadAll()
293                         m.response = Insert(m.response, m.cursorx, clip)
294                         m.cursorx += Count(clip)
295                 case tcell.KeyRune:
296                         m.response = Insert(m.response, m.cursorx, string(e.Rune()))
297                         m.cursorx++
298                 }
299                 history[m.historyNum] = m.response
300
301         case *tcell.EventPaste:
302                 clip := e.Text()
303                 m.response = Insert(m.response, m.cursorx, clip)
304                 m.cursorx += Count(clip)
305         }
306 }
307
308 // Reset resets the messenger's cursor, message and response
309 func (m *Messenger) Reset() {
310         m.cursorx = 0
311         m.message = ""
312         m.response = ""
313 }
314
315 // Clear clears the line at the bottom of the editor
316 func (m *Messenger) Clear() {
317         w, h := screen.Size()
318         for x := 0; x < w; x++ {
319                 screen.SetContent(x, h-1, ' ', nil, defStyle)
320         }
321 }
322
323 func (m *Messenger) DisplaySuggestions(suggestions []string) {
324         w, screenH := screen.Size()
325
326         y := screenH - 2
327
328         statusLineStyle := defStyle.Reverse(true)
329         if style, ok := colorscheme["statusline"]; ok {
330                 statusLineStyle = style
331         }
332
333         for x := 0; x < w; x++ {
334                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
335         }
336
337         x := 0
338         for _, suggestion := range suggestions {
339                 for _, c := range suggestion {
340                         screen.SetContent(x, y, c, nil, statusLineStyle)
341                         x++
342                 }
343                 screen.SetContent(x, y, ' ', nil, statusLineStyle)
344                 x++
345         }
346 }
347
348 // Display displays messages or prompts
349 func (m *Messenger) Display() {
350         _, h := screen.Size()
351         if m.hasMessage {
352                 if m.hasPrompt || globalSettings["infobar"].(bool) {
353                         runes := []rune(m.message + m.response)
354                         for x := 0; x < len(runes); x++ {
355                                 screen.SetContent(x, h-1, runes[x], nil, m.style)
356                         }
357                 }
358         }
359
360         if m.hasPrompt {
361                 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
362                 screen.Show()
363         }
364 }
365
366 // A GutterMessage is a message displayed on the side of the editor
367 type GutterMessage struct {
368         lineNum int
369         msg     string
370         kind    int
371 }
372
373 // These are the different types of messages
374 const (
375         // GutterInfo represents a simple info message
376         GutterInfo = iota
377         // GutterWarning represents a compiler warning
378         GutterWarning
379         // GutterError represents a compiler error
380         GutterError
381 )