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 m.message = fmt.Sprint(msg...)
93 if _, ok := colorscheme["message"]; ok {
94 m.style = colorscheme["message"]
100 // Error sends an error message to the user
101 func (m *Messenger) Error(msg ...interface{}) {
102 buf := new(bytes.Buffer)
103 fmt.Fprint(buf, msg...)
104 m.message = buf.String()
106 Foreground(tcell.ColorBlack).
107 Background(tcell.ColorMaroon)
109 if _, ok := colorscheme["error-message"]; ok {
110 m.style = colorscheme["error-message"]
116 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
117 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
121 _, h := screen.Size()
125 screen.ShowCursor(Count(m.message), h-1)
129 switch e := event.(type) {
130 case *tcell.EventKey:
137 } else if e.Rune() == 'n' {
142 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
143 m.AddLog("\t--> (cancel)")
151 // LetterPrompt gives the user a prompt and waits for a one letter response
152 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
156 _, h := screen.Size()
160 screen.ShowCursor(Count(m.message), h-1)
164 switch e := event.(type) {
165 case *tcell.EventKey:
168 for _, r := range responses {
170 m.AddLog("\t--> " + string(r))
177 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
178 m.AddLog("\t--> (cancel)")
191 NoCompletion Completion = iota
200 // Prompt sends the user a message and waits for a response to be typed in
201 // This function blocks the main loop while waiting for input
202 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
205 if _, ok := m.history[historyType]; !ok {
206 m.history[historyType] = []string{""}
208 m.history[historyType] = append(m.history[historyType], "")
210 m.historyNum = len(m.history[historyType]) - 1
212 response, canceled := placeholder, true
213 m.response = response
214 m.cursorx = Count(placeholder)
218 var suggestions []string
223 switch e := event.(type) {
224 case *tcell.EventKey:
226 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
228 m.AddLog("\t--> (cancel)")
231 // User is done entering their response
232 m.AddLog("\t--> " + m.response)
234 response, canceled = m.response, false
235 m.history[historyType][len(m.history[historyType])-1] = response
237 args := SplitCommandArgs(m.response)
238 currentArgNum := len(args) - 1
239 currentArg := args[currentArgNum]
240 var completionType Completion
242 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
243 if command, ok := commands[args[0]]; ok {
244 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
248 if currentArgNum >= len(completionTypes) {
249 completionType = completionTypes[len(completionTypes)-1]
251 completionType = completionTypes[currentArgNum]
255 if completionType == FileCompletion {
256 chosen, suggestions = FileComplete(currentArg)
257 } else if completionType == CommandCompletion {
258 chosen, suggestions = CommandComplete(currentArg)
259 } else if completionType == HelpCompletion {
260 chosen, suggestions = HelpComplete(currentArg)
261 } else if completionType == OptionCompletion {
262 chosen, suggestions = OptionComplete(currentArg)
263 } else if completionType == PluginCmdCompletion {
264 chosen, suggestions = PluginCmdComplete(currentArg)
265 } else if completionType == PluginNameCompletion {
266 chosen, suggestions = PluginNameComplete(currentArg)
267 } else if completionType < NoCompletion {
268 chosen, suggestions = PluginComplete(completionType, currentArg)
271 if len(suggestions) > 1 {
272 chosen = chosen + CommonSubstring(suggestions...)
276 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
277 m.cursorx = Count(m.response)
282 m.HandleEvent(event, m.history[historyType])
285 for _, v := range tabs[curTab].views {
290 if len(suggestions) > 1 {
291 m.DisplaySuggestions(suggestions)
298 return response, canceled
301 // HandleEvent handles an event for the prompter
302 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
303 switch e := event.(type) {
304 case *tcell.EventKey:
305 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
306 for key, actions := range bindings {
307 if e.Key() == key.keyCode {
308 if e.Key() == tcell.KeyRune {
309 if e.Rune() != key.r {
313 if e.Modifiers() == key.modifiers {
314 for _, action := range actions {
315 funcName := FuncName(action)
317 case "main.(*View).CursorUp":
318 if m.historyNum > 0 {
320 m.response = history[m.historyNum]
321 m.cursorx = Count(m.response)
323 case "main.(*View).CursorDown":
324 if m.historyNum < len(history)-1 {
326 m.response = history[m.historyNum]
327 m.cursorx = Count(m.response)
329 case "main.(*View).CursorLeft":
333 case "main.(*View).CursorRight":
334 if m.cursorx < Count(m.response) {
337 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
339 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
340 m.cursorx = Count(m.response)
341 case "main.(*View).Backspace":
343 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
346 case "main.(*View).Paste":
347 clip, _ := clipboard.ReadAll("clipboard")
348 m.response = Insert(m.response, m.cursorx, clip)
349 m.cursorx += Count(clip)
358 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
361 history[m.historyNum] = m.response
363 case *tcell.EventPaste:
365 m.response = Insert(m.response, m.cursorx, clip)
366 m.cursorx += Count(clip)
367 case *tcell.EventMouse:
369 x -= Count(m.message)
370 button := e.Buttons()
371 _, screenH := screen.Size()
379 } else if m.cursorx > Count(m.response) {
380 m.cursorx = Count(m.response)
387 // Reset resets the messenger's cursor, message and response
388 func (m *Messenger) Reset() {
394 // Clear clears the line at the bottom of the editor
395 func (m *Messenger) Clear() {
396 w, h := screen.Size()
397 for x := 0; x < w; x++ {
398 screen.SetContent(x, h-1, ' ', nil, defStyle)
402 func (m *Messenger) DisplaySuggestions(suggestions []string) {
403 w, screenH := screen.Size()
407 statusLineStyle := defStyle.Reverse(true)
408 if style, ok := colorscheme["statusline"]; ok {
409 statusLineStyle = style
412 for x := 0; x < w; x++ {
413 screen.SetContent(x, y, ' ', nil, statusLineStyle)
417 for _, suggestion := range suggestions {
418 for _, c := range suggestion {
419 screen.SetContent(x, y, c, nil, statusLineStyle)
422 screen.SetContent(x, y, ' ', nil, statusLineStyle)
427 // Display displays messages or prompts
428 func (m *Messenger) Display() {
429 _, h := screen.Size()
431 if m.hasPrompt || globalSettings["infobar"].(bool) {
432 runes := []rune(m.message + m.response)
433 for x := 0; x < len(runes); x++ {
434 screen.SetContent(x, h-1, runes[x], nil, m.style)
440 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
445 // A GutterMessage is a message displayed on the side of the editor
446 type GutterMessage struct {
452 // These are the different types of messages
454 // GutterInfo represents a simple info message
456 // GutterWarning represents a compiler warning
458 // GutterError represents a compiler error