10 "github.com/zyedidia/clipboard"
11 "github.com/zyedidia/tcell"
14 // TermMessage sends a message to the user in the terminal. This usually occurs before
15 // micro has been fully initialized -- ie if there is an error in the syntax highlighting
16 // regular expressions
17 // The function must be called when the screen is not initialized
18 // This will write the message, and wait for the user
19 // to press and key to continue
20 func TermMessage(msg ...interface{}) {
21 screenWasNil := screen == nil
27 messenger.AddLog(fmt.Sprint(msg...))
28 fmt.Print("\nPress enter to continue")
30 reader := bufio.NewReader(os.Stdin)
31 reader.ReadString('\n')
38 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
40 func TermError(filename string, lineNum int, err string) {
41 TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
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 {
48 // Are we currently prompting the user?
50 // Is there a message to print
55 // The user's response to a prompt
57 // style to use when drawing the message
60 // We have to keep track of the cursor for prompting
63 // This map stores the history for all the different kinds of uses Prompt has
64 // It's a map of history type -> history array
65 history map[string][]string
68 // Is the current message a message from the gutter
72 func (m *Messenger) AddLog(msg string) {
73 buffer := m.getBuffer()
74 buffer.insert(buffer.End(), []byte(msg+"\n"))
75 buffer.Cursor.Loc = buffer.End()
76 buffer.Cursor.Relocate()
79 func (m *Messenger) getBuffer() *Buffer {
81 m.log = NewBuffer([]byte{}, "")
87 // Message sends a message to the user
88 func (m *Messenger) Message(msg ...interface{}) {
89 m.message = fmt.Sprint(msg...)
92 if _, ok := colorscheme["message"]; ok {
93 m.style = colorscheme["message"]
99 // Error sends an error message to the user
100 func (m *Messenger) Error(msg ...interface{}) {
101 buf := new(bytes.Buffer)
102 fmt.Fprint(buf, msg...)
103 m.message = buf.String()
105 Foreground(tcell.ColorBlack).
106 Background(tcell.ColorMaroon)
108 if _, ok := colorscheme["error-message"]; ok {
109 m.style = colorscheme["error-message"]
115 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
116 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
120 _, h := screen.Size()
124 screen.ShowCursor(Count(m.message), h-1)
128 switch e := event.(type) {
129 case *tcell.EventKey:
136 } else if e.Rune() == 'n' {
141 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
142 m.AddLog("\t--> (cancel)")
150 // LetterPrompt gives the user a prompt and waits for a one letter response
151 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
155 _, h := screen.Size()
159 screen.ShowCursor(Count(m.message), h-1)
163 switch e := event.(type) {
164 case *tcell.EventKey:
167 for _, r := range responses {
169 m.AddLog("\t--> " + string(r))
176 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
177 m.AddLog("\t--> (cancel)")
190 NoCompletion Completion = iota
197 // Prompt sends the user a message and waits for a response to be typed in
198 // This function blocks the main loop while waiting for input
199 func (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {
202 if _, ok := m.history[historyType]; !ok {
203 m.history[historyType] = []string{""}
205 m.history[historyType] = append(m.history[historyType], "")
207 m.historyNum = len(m.history[historyType]) - 1
209 response, canceled := "", true
213 var suggestions []string
218 switch e := event.(type) {
219 case *tcell.EventKey:
221 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
223 m.AddLog("\t--> (cancel)")
226 // User is done entering their response
227 m.AddLog("\t--> " + m.response)
229 response, canceled = m.response, false
230 m.history[historyType][len(m.history[historyType])-1] = response
232 args := SplitCommandArgs(m.response)
233 currentArgNum := len(args) - 1
234 currentArg := args[currentArgNum]
235 var completionType Completion
237 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
238 if command, ok := commands[args[0]]; ok {
239 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
243 if currentArgNum >= len(completionTypes) {
244 completionType = completionTypes[len(completionTypes)-1]
246 completionType = completionTypes[currentArgNum]
250 if completionType == FileCompletion {
251 chosen, suggestions = FileComplete(currentArg)
252 } else if completionType == CommandCompletion {
253 chosen, suggestions = CommandComplete(currentArg)
254 } else if completionType == HelpCompletion {
255 chosen, suggestions = HelpComplete(currentArg)
256 } else if completionType == OptionCompletion {
257 chosen, suggestions = OptionComplete(currentArg)
258 } else if completionType < NoCompletion {
259 chosen, suggestions = PluginComplete(completionType, currentArg)
262 if len(suggestions) > 1 {
263 chosen = chosen + CommonSubstring(suggestions...)
267 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
268 m.cursorx = Count(m.response)
273 m.HandleEvent(event, m.history[historyType])
276 for _, v := range tabs[curTab].views {
281 if len(suggestions) > 1 {
282 m.DisplaySuggestions(suggestions)
289 return response, canceled
292 // HandleEvent handles an event for the prompter
293 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
294 switch e := event.(type) {
295 case *tcell.EventKey:
296 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
297 for key, actions := range bindings {
298 if e.Key() == key.keyCode {
299 if e.Key() == tcell.KeyRune {
300 if e.Rune() != key.r {
304 if e.Modifiers() == key.modifiers {
305 for _, action := range actions {
306 funcName := FuncName(action)
308 case "main.(*View).CursorUp":
309 if m.historyNum > 0 {
311 m.response = history[m.historyNum]
312 m.cursorx = Count(m.response)
314 case "main.(*View).CursorDown":
315 if m.historyNum < len(history)-1 {
317 m.response = history[m.historyNum]
318 m.cursorx = Count(m.response)
320 case "main.(*View).CursorLeft":
324 case "main.(*View).CursorRight":
325 if m.cursorx < Count(m.response) {
328 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
330 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
331 m.cursorx = Count(m.response)
332 case "main.(*View).Backspace":
334 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
337 case "main.(*View).Paste":
338 clip, _ := clipboard.ReadAll("clipboard")
339 m.response = Insert(m.response, m.cursorx, clip)
340 m.cursorx += Count(clip)
349 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
352 history[m.historyNum] = m.response
354 case *tcell.EventPaste:
356 m.response = Insert(m.response, m.cursorx, clip)
357 m.cursorx += Count(clip)
358 case *tcell.EventMouse:
360 x -= Count(m.message)
361 button := e.Buttons()
362 _, screenH := screen.Size()
370 } else if m.cursorx > Count(m.response) {
371 m.cursorx = Count(m.response)
378 // Reset resets the messenger's cursor, message and response
379 func (m *Messenger) Reset() {
385 // Clear clears the line at the bottom of the editor
386 func (m *Messenger) Clear() {
387 w, h := screen.Size()
388 for x := 0; x < w; x++ {
389 screen.SetContent(x, h-1, ' ', nil, defStyle)
393 func (m *Messenger) DisplaySuggestions(suggestions []string) {
394 w, screenH := screen.Size()
398 statusLineStyle := defStyle.Reverse(true)
399 if style, ok := colorscheme["statusline"]; ok {
400 statusLineStyle = style
403 for x := 0; x < w; x++ {
404 screen.SetContent(x, y, ' ', nil, statusLineStyle)
408 for _, suggestion := range suggestions {
409 for _, c := range suggestion {
410 screen.SetContent(x, y, c, nil, statusLineStyle)
413 screen.SetContent(x, y, ' ', nil, statusLineStyle)
418 // Display displays messages or prompts
419 func (m *Messenger) Display() {
420 _, h := screen.Size()
422 if m.hasPrompt || globalSettings["infobar"].(bool) {
423 runes := []rune(m.message + m.response)
424 for x := 0; x < len(runes); x++ {
425 screen.SetContent(x, h-1, runes[x], nil, m.style)
431 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
436 // A GutterMessage is a message displayed on the side of the editor
437 type GutterMessage struct {
443 // These are the different types of messages
445 // GutterInfo represents a simple info message
447 // GutterWarning represents a compiler warning
449 // GutterError represents a compiler error