10 "github.com/zyedidia/clipboard"
11 "github.com/zyedidia/tcell"
12 "github.com/mattn/go-runewidth"
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
29 fmt.Print("\nPress enter to continue")
31 reader := bufio.NewReader(os.Stdin)
32 reader.ReadString('\n')
39 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
41 func TermError(filename string, lineNum int, err string) {
42 TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
45 // Messenger is an object that makes it easy to send messages to the user
46 // and get input from the user
47 type Messenger struct {
49 // Are we currently prompting the user?
51 // Is there a message to print
56 // The user's response to a prompt
58 // style to use when drawing the message
61 // We have to keep track of the cursor for prompting
64 // This map stores the history for all the different kinds of uses Prompt has
65 // It's a map of history type -> history array
66 history map[string][]string
69 // Is the current message a message from the gutter
73 func (m *Messenger) AddLog(msg string) {
74 buffer := m.getBuffer()
75 buffer.insert(buffer.End(), []byte(msg+"\n"))
76 buffer.Cursor.Loc = buffer.End()
77 buffer.Cursor.Relocate()
80 func (m *Messenger) getBuffer() *Buffer {
82 m.log = NewBufferFromString("", "")
88 // Message sends a message to the user
89 func (m *Messenger) Message(msg ...interface{}) {
90 displayMessage := fmt.Sprint(msg...)
91 // only display a new message if there isn't an active prompt
92 // this is to prevent overwriting an existing prompt to the user
93 if m.hasPrompt == false {
94 // if there is no active prompt then style and display the message as normal
95 m.message = displayMessage
99 if _, ok := colorscheme["message"]; ok {
100 m.style = colorscheme["message"]
105 // add the message to the log regardless of active prompts
106 m.AddLog(displayMessage)
109 // Error sends an error message to the user
110 func (m *Messenger) Error(msg ...interface{}) {
111 buf := new(bytes.Buffer)
112 fmt.Fprint(buf, msg...)
114 // only display a new message if there isn't an active prompt
115 // this is to prevent overwriting an existing prompt to the user
116 if m.hasPrompt == false {
117 // if there is no active prompt then style and display the message as normal
118 m.message = buf.String()
120 Foreground(tcell.ColorBlack).
121 Background(tcell.ColorMaroon)
123 if _, ok := colorscheme["error-message"]; ok {
124 m.style = colorscheme["error-message"]
128 // add the message to the log regardless of active prompts
129 m.AddLog(buf.String())
132 func (m *Messenger) PromptText(msg ...interface{}) {
133 displayMessage := fmt.Sprint(msg...)
134 // if there is no active prompt then style and display the message as normal
135 m.message = displayMessage
139 if _, ok := colorscheme["message"]; ok {
140 m.style = colorscheme["message"]
144 // add the message to the log regardless of active prompts
145 m.AddLog(displayMessage)
148 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
149 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
153 _, h := screen.Size()
157 screen.ShowCursor(Count(m.message), h-1)
161 switch e := event.(type) {
162 case *tcell.EventKey:
165 if e.Rune() == 'y' || e.Rune() == 'Y' {
169 } else if e.Rune() == 'n' || e.Rune() == 'N' {
174 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
175 m.AddLog("\t--> (cancel)")
185 // LetterPrompt gives the user a prompt and waits for a one letter response
186 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
190 _, h := screen.Size()
194 screen.ShowCursor(Count(m.message), h-1)
198 switch e := event.(type) {
199 case *tcell.EventKey:
202 for _, r := range responses {
204 m.AddLog("\t--> " + string(r))
211 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
212 m.AddLog("\t--> (cancel)")
225 NoCompletion Completion = iota
234 // Prompt sends the user a message and waits for a response to be typed in
235 // This function blocks the main loop while waiting for input
236 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
239 if _, ok := m.history[historyType]; !ok {
240 m.history[historyType] = []string{""}
242 m.history[historyType] = append(m.history[historyType], "")
244 m.historyNum = len(m.history[historyType]) - 1
246 response, canceled := placeholder, true
247 m.response = response
248 m.cursorx = Count(placeholder)
252 var suggestions []string
257 switch e := event.(type) {
258 case *tcell.EventKey:
260 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
262 m.AddLog("\t--> (cancel)")
265 // User is done entering their response
266 m.AddLog("\t--> " + m.response)
268 response, canceled = m.response, false
269 m.history[historyType][len(m.history[historyType])-1] = response
271 args := SplitCommandArgs(m.response)
272 currentArgNum := len(args) - 1
273 currentArg := args[currentArgNum]
274 var completionType Completion
276 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
277 if command, ok := commands[args[0]]; ok {
278 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
282 if currentArgNum >= len(completionTypes) {
283 completionType = completionTypes[len(completionTypes)-1]
285 completionType = completionTypes[currentArgNum]
289 if completionType == FileCompletion {
290 chosen, suggestions = FileComplete(currentArg)
291 } else if completionType == CommandCompletion {
292 chosen, suggestions = CommandComplete(currentArg)
293 } else if completionType == HelpCompletion {
294 chosen, suggestions = HelpComplete(currentArg)
295 } else if completionType == OptionCompletion {
296 chosen, suggestions = OptionComplete(currentArg)
297 } else if completionType == PluginCmdCompletion {
298 chosen, suggestions = PluginCmdComplete(currentArg)
299 } else if completionType == PluginNameCompletion {
300 chosen, suggestions = PluginNameComplete(currentArg)
301 } else if completionType < NoCompletion {
302 chosen, suggestions = PluginComplete(completionType, currentArg)
305 if len(suggestions) > 1 {
306 chosen = chosen + CommonSubstring(suggestions...)
310 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
311 m.cursorx = Count(m.response)
316 m.HandleEvent(event, m.history[historyType])
319 for _, v := range tabs[curTab].views {
324 if len(suggestions) > 1 {
325 m.DisplaySuggestions(suggestions)
332 return response, canceled
335 // HandleEvent handles an event for the prompter
336 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
337 switch e := event.(type) {
338 case *tcell.EventKey:
339 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
340 for key, actions := range bindings {
341 if e.Key() == key.keyCode {
342 if e.Key() == tcell.KeyRune {
343 if e.Rune() != key.r {
347 if e.Modifiers() == key.modifiers {
348 for _, action := range actions {
349 funcName := FuncName(action)
351 case "main.(*View).CursorUp":
352 if m.historyNum > 0 {
354 m.response = history[m.historyNum]
355 m.cursorx = Count(m.response)
357 case "main.(*View).CursorDown":
358 if m.historyNum < len(history)-1 {
360 m.response = history[m.historyNum]
361 m.cursorx = Count(m.response)
363 case "main.(*View).CursorLeft":
367 case "main.(*View).CursorRight":
368 if m.cursorx < Count(m.response) {
371 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
373 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
374 m.cursorx = Count(m.response)
375 case "main.(*View).Backspace":
377 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
380 case "main.(*View).Paste":
381 clip, _ := clipboard.ReadAll("clipboard")
382 m.response = Insert(m.response, m.cursorx, clip)
383 m.cursorx += Count(clip)
392 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
395 history[m.historyNum] = m.response
397 case *tcell.EventPaste:
399 m.response = Insert(m.response, m.cursorx, clip)
400 m.cursorx += Count(clip)
401 case *tcell.EventMouse:
403 x -= Count(m.message)
404 button := e.Buttons()
405 _, screenH := screen.Size()
413 } else if m.cursorx > Count(m.response) {
414 m.cursorx = Count(m.response)
421 // Reset resets the messenger's cursor, message and response
422 func (m *Messenger) Reset() {
428 // Clear clears the line at the bottom of the editor
429 func (m *Messenger) Clear() {
430 w, h := screen.Size()
431 for x := 0; x < w; x++ {
432 screen.SetContent(x, h-1, ' ', nil, defStyle)
436 func (m *Messenger) DisplaySuggestions(suggestions []string) {
437 w, screenH := screen.Size()
441 statusLineStyle := defStyle.Reverse(true)
442 if style, ok := colorscheme["statusline"]; ok {
443 statusLineStyle = style
446 for x := 0; x < w; x++ {
447 screen.SetContent(x, y, ' ', nil, statusLineStyle)
451 for _, suggestion := range suggestions {
452 for _, c := range suggestion {
453 screen.SetContent(x, y, c, nil, statusLineStyle)
456 screen.SetContent(x, y, ' ', nil, statusLineStyle)
461 // Display displays messages or prompts
462 func (m *Messenger) Display() {
463 _, h := screen.Size()
465 if m.hasPrompt || globalSettings["infobar"].(bool) {
466 runes := []rune(m.message + m.response)
468 for x := 0; x < len(runes); x++ {
469 screen.SetContent(posx, h-1, runes[x], nil, m.style)
470 posx += runewidth.RuneWidth(runes[x])
476 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
481 // A GutterMessage is a message displayed on the side of the editor
482 type GutterMessage struct {
488 // These are the different types of messages
490 // GutterInfo represents a simple info message
492 // GutterWarning represents a compiler warning
494 // GutterError represents a compiler error