]> git.lizzy.rs Git - micro.git/blob - cmd/micro/messenger.go
24964ea0880eb48eaff1f5e3c752586a428fa65b
[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/tcell"
11 )
12
13 // TermMessage sends a message to the user in the terminal. This usually occurs before
14 // micro has been fully initialized -- ie if there is an error in the syntax highlighting
15 // regular expressions
16 // The function must be called when the screen is not initialized
17 // This will write the message, and wait for the user
18 // to press and key to continue
19 func TermMessage(msg ...interface{}) {
20         screenWasNil := screen == nil
21         if !screenWasNil {
22                 screen.Fini()
23         }
24
25         fmt.Println(msg...)
26         fmt.Print("\nPress enter to continue")
27
28         reader := bufio.NewReader(os.Stdin)
29         reader.ReadString('\n')
30
31         if !screenWasNil {
32                 InitScreen()
33         }
34 }
35
36 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
37 // as an error
38 func TermError(filename string, lineNum int, err string) {
39         TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
40 }
41
42 // Messenger is an object that makes it easy to send messages to the user
43 // and get input from the user
44 type Messenger struct {
45         // Are we currently prompting the user?
46         hasPrompt bool
47         // Is there a message to print
48         hasMessage bool
49
50         // Message to print
51         message string
52         // The user's response to a prompt
53         response string
54         // style to use when drawing the message
55         style tcell.Style
56
57         // We have to keep track of the cursor for prompting
58         cursorx int
59
60         // This map stores the history for all the different kinds of uses Prompt has
61         // It's a map of history type -> history array
62         history    map[string][]string
63         historyNum int
64
65         // Is the current message a message from the gutter
66         gutterMessage bool
67 }
68
69 // Message sends a message to the user
70 func (m *Messenger) Message(msg ...interface{}) {
71         buf := new(bytes.Buffer)
72         fmt.Fprint(buf, msg...)
73         m.message = buf.String()
74         m.style = defStyle
75
76         if _, ok := colorscheme["message"]; ok {
77                 m.style = colorscheme["message"]
78         }
79         m.hasMessage = true
80 }
81
82 // Error sends an error message to the user
83 func (m *Messenger) Error(msg ...interface{}) {
84         buf := new(bytes.Buffer)
85         fmt.Fprint(buf, msg...)
86         m.message = buf.String()
87         m.style = defStyle.
88                 Foreground(tcell.ColorBlack).
89                 Background(tcell.ColorMaroon)
90
91         if _, ok := colorscheme["error-message"]; ok {
92                 m.style = colorscheme["error-message"]
93         }
94         m.hasMessage = true
95 }
96
97 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
98 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
99         m.Message(prompt)
100
101         for {
102                 m.Clear()
103                 m.Display()
104                 screen.Show()
105                 event := screen.PollEvent()
106
107                 switch e := event.(type) {
108                 case *tcell.EventKey:
109                         switch e.Key() {
110                         case tcell.KeyRune:
111                                 if e.Rune() == 'y' {
112                                         return true, false
113                                 } else if e.Rune() == 'n' {
114                                         return false, false
115                                 }
116                         case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
117                                 return false, true
118                         }
119                 }
120         }
121 }
122
123 // Prompt sends the user a message and waits for a response to be typed in
124 // This function blocks the main loop while waiting for input
125 func (m *Messenger) Prompt(prompt, historyType string) (string, bool) {
126         m.hasPrompt = true
127         m.Message(prompt)
128         if _, ok := m.history[historyType]; !ok {
129                 m.history[historyType] = []string{""}
130         } else {
131                 m.history[historyType] = append(m.history[historyType], "")
132         }
133         m.historyNum = len(m.history[historyType]) - 1
134
135         response, canceled := "", true
136
137         for m.hasPrompt {
138                 m.Clear()
139                 m.Display()
140
141                 event := screen.PollEvent()
142
143                 switch e := event.(type) {
144                 case *tcell.EventKey:
145                         switch e.Key() {
146                         case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
147                                 // Cancel
148                                 m.hasPrompt = false
149                         case tcell.KeyEnter:
150                                 // User is done entering their response
151                                 m.hasPrompt = false
152                                 response, canceled = m.response, false
153                                 m.history[historyType][len(m.history[historyType])-1] = response
154                         }
155                 }
156
157                 m.HandleEvent(event, m.history[historyType])
158
159                 if m.cursorx < 0 {
160                         // Cancel
161                         m.hasPrompt = false
162                 }
163         }
164
165         m.Reset()
166         return response, canceled
167 }
168
169 // HandleEvent handles an event for the prompter
170 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
171         switch e := event.(type) {
172         case *tcell.EventKey:
173                 switch e.Key() {
174                 case tcell.KeyUp:
175                         if m.historyNum > 0 {
176                                 m.historyNum--
177                                 m.response = history[m.historyNum]
178                                 m.cursorx = len(m.response)
179                         }
180                 case tcell.KeyDown:
181                         if m.historyNum < len(history)-1 {
182                                 m.historyNum++
183                                 m.response = history[m.historyNum]
184                                 m.cursorx = len(m.response)
185                         }
186                 case tcell.KeyLeft:
187                         if m.cursorx > 0 {
188                                 m.cursorx--
189                         }
190                 case tcell.KeyRight:
191                         if m.cursorx < Count(m.response) {
192                                 m.cursorx++
193                         }
194                 case tcell.KeyBackspace2, tcell.KeyBackspace:
195                         if m.cursorx > 0 {
196                                 m.response = string([]rune(m.response)[:m.cursorx-1]) + string(m.response[m.cursorx:])
197                         }
198                         m.cursorx--
199                 case tcell.KeyRune:
200                         m.response = Insert(m.response, m.cursorx, string(e.Rune()))
201                         m.cursorx++
202                 }
203                 history[m.historyNum] = m.response
204         }
205 }
206
207 // Reset resets the messenger's cursor, message and response
208 func (m *Messenger) Reset() {
209         m.cursorx = 0
210         m.message = ""
211         m.response = ""
212 }
213
214 // Clear clears the line at the bottom of the editor
215 func (m *Messenger) Clear() {
216         w, h := screen.Size()
217         for x := 0; x < w; x++ {
218                 screen.SetContent(x, h-1, ' ', nil, defStyle)
219         }
220 }
221
222 // Display displays messages or prompts
223 func (m *Messenger) Display() {
224         _, h := screen.Size()
225         if m.hasMessage {
226                 runes := []rune(m.message + m.response)
227                 for x := 0; x < len(runes); x++ {
228                         screen.SetContent(x, h-1, runes[x], nil, m.style)
229                 }
230         }
231         if m.hasPrompt {
232                 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
233                 screen.Show()
234         }
235 }
236
237 // A GutterMessage is a message displayed on the side of the editor
238 type GutterMessage struct {
239         lineNum int
240         msg     string
241         kind    int
242 }
243
244 // These are the different types of messages
245 const (
246         // GutterInfo represents a simple info message
247         GutterInfo = iota
248         // GutterWarning represents a compiler warning
249         GutterWarning
250         // GutterError represents a compiler error
251         GutterError
252 )