11 "github.com/zyedidia/clipboard"
12 "github.com/zyedidia/tcell"
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 = NewBuffer(strings.NewReader(""), "")
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:
169 } else if e.Rune() == 'n' {
174 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
175 m.AddLog("\t--> (cancel)")
183 // LetterPrompt gives the user a prompt and waits for a one letter response
184 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
188 _, h := screen.Size()
192 screen.ShowCursor(Count(m.message), h-1)
196 switch e := event.(type) {
197 case *tcell.EventKey:
200 for _, r := range responses {
202 m.AddLog("\t--> " + string(r))
209 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
210 m.AddLog("\t--> (cancel)")
223 NoCompletion Completion = iota
232 // Prompt sends the user a message and waits for a response to be typed in
233 // This function blocks the main loop while waiting for input
234 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
237 if _, ok := m.history[historyType]; !ok {
238 m.history[historyType] = []string{""}
240 m.history[historyType] = append(m.history[historyType], "")
242 m.historyNum = len(m.history[historyType]) - 1
244 response, canceled := placeholder, true
245 m.response = response
246 m.cursorx = Count(placeholder)
250 var suggestions []string
255 switch e := event.(type) {
256 case *tcell.EventKey:
258 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
260 m.AddLog("\t--> (cancel)")
263 // User is done entering their response
264 m.AddLog("\t--> " + m.response)
266 response, canceled = m.response, false
267 m.history[historyType][len(m.history[historyType])-1] = response
269 args := SplitCommandArgs(m.response)
270 currentArgNum := len(args) - 1
271 currentArg := args[currentArgNum]
272 var completionType Completion
274 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
275 if command, ok := commands[args[0]]; ok {
276 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
280 if currentArgNum >= len(completionTypes) {
281 completionType = completionTypes[len(completionTypes)-1]
283 completionType = completionTypes[currentArgNum]
287 if completionType == FileCompletion {
288 chosen, suggestions = FileComplete(currentArg)
289 } else if completionType == CommandCompletion {
290 chosen, suggestions = CommandComplete(currentArg)
291 } else if completionType == HelpCompletion {
292 chosen, suggestions = HelpComplete(currentArg)
293 } else if completionType == OptionCompletion {
294 chosen, suggestions = OptionComplete(currentArg)
295 } else if completionType == PluginCmdCompletion {
296 chosen, suggestions = PluginCmdComplete(currentArg)
297 } else if completionType == PluginNameCompletion {
298 chosen, suggestions = PluginNameComplete(currentArg)
299 } else if completionType < NoCompletion {
300 chosen, suggestions = PluginComplete(completionType, currentArg)
303 if len(suggestions) > 1 {
304 chosen = chosen + CommonSubstring(suggestions...)
308 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
309 m.cursorx = Count(m.response)
314 m.HandleEvent(event, m.history[historyType])
317 for _, v := range tabs[curTab].views {
322 if len(suggestions) > 1 {
323 m.DisplaySuggestions(suggestions)
330 return response, canceled
333 // HandleEvent handles an event for the prompter
334 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
335 switch e := event.(type) {
336 case *tcell.EventKey:
337 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
338 for key, actions := range bindings {
339 if e.Key() == key.keyCode {
340 if e.Key() == tcell.KeyRune {
341 if e.Rune() != key.r {
345 if e.Modifiers() == key.modifiers {
346 for _, action := range actions {
347 funcName := FuncName(action)
349 case "main.(*View).CursorUp":
350 if m.historyNum > 0 {
352 m.response = history[m.historyNum]
353 m.cursorx = Count(m.response)
355 case "main.(*View).CursorDown":
356 if m.historyNum < len(history)-1 {
358 m.response = history[m.historyNum]
359 m.cursorx = Count(m.response)
361 case "main.(*View).CursorLeft":
365 case "main.(*View).CursorRight":
366 if m.cursorx < Count(m.response) {
369 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
371 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
372 m.cursorx = Count(m.response)
373 case "main.(*View).Backspace":
375 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
378 case "main.(*View).Paste":
379 clip, _ := clipboard.ReadAll("clipboard")
380 m.response = Insert(m.response, m.cursorx, clip)
381 m.cursorx += Count(clip)
390 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
393 history[m.historyNum] = m.response
395 case *tcell.EventPaste:
397 m.response = Insert(m.response, m.cursorx, clip)
398 m.cursorx += Count(clip)
399 case *tcell.EventMouse:
401 x -= Count(m.message)
402 button := e.Buttons()
403 _, screenH := screen.Size()
411 } else if m.cursorx > Count(m.response) {
412 m.cursorx = Count(m.response)
419 // Reset resets the messenger's cursor, message and response
420 func (m *Messenger) Reset() {
426 // Clear clears the line at the bottom of the editor
427 func (m *Messenger) Clear() {
428 w, h := screen.Size()
429 for x := 0; x < w; x++ {
430 screen.SetContent(x, h-1, ' ', nil, defStyle)
434 func (m *Messenger) DisplaySuggestions(suggestions []string) {
435 w, screenH := screen.Size()
439 statusLineStyle := defStyle.Reverse(true)
440 if style, ok := colorscheme["statusline"]; ok {
441 statusLineStyle = style
444 for x := 0; x < w; x++ {
445 screen.SetContent(x, y, ' ', nil, statusLineStyle)
449 for _, suggestion := range suggestions {
450 for _, c := range suggestion {
451 screen.SetContent(x, y, c, nil, statusLineStyle)
454 screen.SetContent(x, y, ' ', nil, statusLineStyle)
459 // Display displays messages or prompts
460 func (m *Messenger) Display() {
461 _, h := screen.Size()
463 if m.hasPrompt || globalSettings["infobar"].(bool) {
464 runes := []rune(m.message + m.response)
465 for x := 0; x < len(runes); x++ {
466 screen.SetContent(x, h-1, runes[x], nil, m.style)
472 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
477 // A GutterMessage is a message displayed on the side of the editor
478 type GutterMessage struct {
484 // These are the different types of messages
486 // GutterInfo represents a simple info message
488 // GutterWarning represents a compiler warning
490 // GutterError represents a compiler error