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