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