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
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 = NewBufferFromString("", "")
87 // Message sends a message to the user
88 func (m *Messenger) Message(msg ...interface{}) {
89 displayMessage := fmt.Sprint(msg...)
90 // only display a new message if there isn't an active prompt
91 // this is to prevent overwriting an existing prompt to the user
92 if m.hasPrompt == false {
93 // if there is no active prompt then style and display the message as normal
94 m.message = displayMessage
98 if _, ok := colorscheme["message"]; ok {
99 m.style = colorscheme["message"]
104 // add the message to the log regardless of active prompts
105 m.AddLog(displayMessage)
108 // Error sends an error message to the user
109 func (m *Messenger) Error(msg ...interface{}) {
110 buf := new(bytes.Buffer)
111 fmt.Fprint(buf, msg...)
113 // only display a new message if there isn't an active prompt
114 // this is to prevent overwriting an existing prompt to the user
115 if m.hasPrompt == false {
116 // if there is no active prompt then style and display the message as normal
117 m.message = buf.String()
119 Foreground(tcell.ColorBlack).
120 Background(tcell.ColorMaroon)
122 if _, ok := colorscheme["error-message"]; ok {
123 m.style = colorscheme["error-message"]
127 // add the message to the log regardless of active prompts
128 m.AddLog(buf.String())
131 func (m *Messenger) PromptText(msg ...interface{}) {
132 displayMessage := fmt.Sprint(msg...)
133 // if there is no active prompt then style and display the message as normal
134 m.message = displayMessage
138 if _, ok := colorscheme["message"]; ok {
139 m.style = colorscheme["message"]
143 // add the message to the log regardless of active prompts
144 m.AddLog(displayMessage)
147 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
148 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
152 _, h := screen.Size()
156 screen.ShowCursor(Count(m.message), h-1)
160 switch e := event.(type) {
161 case *tcell.EventKey:
168 } else if e.Rune() == 'n' {
173 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
174 m.AddLog("\t--> (cancel)")
182 // LetterPrompt gives the user a prompt and waits for a one letter response
183 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
187 _, h := screen.Size()
191 screen.ShowCursor(Count(m.message), h-1)
195 switch e := event.(type) {
196 case *tcell.EventKey:
199 for _, r := range responses {
201 m.AddLog("\t--> " + string(r))
208 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
209 m.AddLog("\t--> (cancel)")
222 NoCompletion Completion = iota
231 // Prompt sends the user a message and waits for a response to be typed in
232 // This function blocks the main loop while waiting for input
233 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
236 if _, ok := m.history[historyType]; !ok {
237 m.history[historyType] = []string{""}
239 m.history[historyType] = append(m.history[historyType], "")
241 m.historyNum = len(m.history[historyType]) - 1
243 response, canceled := placeholder, true
244 m.response = response
245 m.cursorx = Count(placeholder)
249 var suggestions []string
254 switch e := event.(type) {
255 case *tcell.EventKey:
257 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
259 m.AddLog("\t--> (cancel)")
262 // User is done entering their response
263 m.AddLog("\t--> " + m.response)
265 response, canceled = m.response, false
266 m.history[historyType][len(m.history[historyType])-1] = response
268 args := SplitCommandArgs(m.response)
269 currentArgNum := len(args) - 1
270 currentArg := args[currentArgNum]
271 var completionType Completion
273 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
274 if command, ok := commands[args[0]]; ok {
275 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
279 if currentArgNum >= len(completionTypes) {
280 completionType = completionTypes[len(completionTypes)-1]
282 completionType = completionTypes[currentArgNum]
286 if completionType == FileCompletion {
287 chosen, suggestions = FileComplete(currentArg)
288 } else if completionType == CommandCompletion {
289 chosen, suggestions = CommandComplete(currentArg)
290 } else if completionType == HelpCompletion {
291 chosen, suggestions = HelpComplete(currentArg)
292 } else if completionType == OptionCompletion {
293 chosen, suggestions = OptionComplete(currentArg)
294 } else if completionType == PluginCmdCompletion {
295 chosen, suggestions = PluginCmdComplete(currentArg)
296 } else if completionType == PluginNameCompletion {
297 chosen, suggestions = PluginNameComplete(currentArg)
298 } else if completionType < NoCompletion {
299 chosen, suggestions = PluginComplete(completionType, currentArg)
302 if len(suggestions) > 1 {
303 chosen = chosen + CommonSubstring(suggestions...)
307 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
308 m.cursorx = Count(m.response)
313 m.HandleEvent(event, m.history[historyType])
316 for _, v := range tabs[curTab].views {
321 if len(suggestions) > 1 {
322 m.DisplaySuggestions(suggestions)
329 return response, canceled
332 // HandleEvent handles an event for the prompter
333 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
334 switch e := event.(type) {
335 case *tcell.EventKey:
336 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
337 for key, actions := range bindings {
338 if e.Key() == key.keyCode {
339 if e.Key() == tcell.KeyRune {
340 if e.Rune() != key.r {
344 if e.Modifiers() == key.modifiers {
345 for _, action := range actions {
346 funcName := FuncName(action)
348 case "main.(*View).CursorUp":
349 if m.historyNum > 0 {
351 m.response = history[m.historyNum]
352 m.cursorx = Count(m.response)
354 case "main.(*View).CursorDown":
355 if m.historyNum < len(history)-1 {
357 m.response = history[m.historyNum]
358 m.cursorx = Count(m.response)
360 case "main.(*View).CursorLeft":
364 case "main.(*View).CursorRight":
365 if m.cursorx < Count(m.response) {
368 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
370 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
371 m.cursorx = Count(m.response)
372 case "main.(*View).Backspace":
374 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
377 case "main.(*View).Paste":
378 clip, _ := clipboard.ReadAll("clipboard")
379 m.response = Insert(m.response, m.cursorx, clip)
380 m.cursorx += Count(clip)
389 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
392 history[m.historyNum] = m.response
394 case *tcell.EventPaste:
396 m.response = Insert(m.response, m.cursorx, clip)
397 m.cursorx += Count(clip)
398 case *tcell.EventMouse:
400 x -= Count(m.message)
401 button := e.Buttons()
402 _, screenH := screen.Size()
410 } else if m.cursorx > Count(m.response) {
411 m.cursorx = Count(m.response)
418 // Reset resets the messenger's cursor, message and response
419 func (m *Messenger) Reset() {
425 // Clear clears the line at the bottom of the editor
426 func (m *Messenger) Clear() {
427 w, h := screen.Size()
428 for x := 0; x < w; x++ {
429 screen.SetContent(x, h-1, ' ', nil, defStyle)
433 func (m *Messenger) DisplaySuggestions(suggestions []string) {
434 w, screenH := screen.Size()
438 statusLineStyle := defStyle.Reverse(true)
439 if style, ok := colorscheme["statusline"]; ok {
440 statusLineStyle = style
443 for x := 0; x < w; x++ {
444 screen.SetContent(x, y, ' ', nil, statusLineStyle)
448 for _, suggestion := range suggestions {
449 for _, c := range suggestion {
450 screen.SetContent(x, y, c, nil, statusLineStyle)
453 screen.SetContent(x, y, ' ', nil, statusLineStyle)
458 // Display displays messages or prompts
459 func (m *Messenger) Display() {
460 _, h := screen.Size()
462 if m.hasPrompt || globalSettings["infobar"].(bool) {
463 runes := []rune(m.message + m.response)
464 for x := 0; x < len(runes); x++ {
465 screen.SetContent(x, h-1, runes[x], nil, m.style)
471 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
476 // A GutterMessage is a message displayed on the side of the editor
477 type GutterMessage struct {
483 // These are the different types of messages
485 // GutterInfo represents a simple info message
487 // GutterWarning represents a compiler warning
489 // GutterError represents a compiler error