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 = 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
199 // Prompt sends the user a message and waits for a response to be typed in
200 // This function blocks the main loop while waiting for input
201 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
204 if _, ok := m.history[historyType]; !ok {
205 m.history[historyType] = []string{""}
207 m.history[historyType] = append(m.history[historyType], "")
209 m.historyNum = len(m.history[historyType]) - 1
211 response, canceled := placeholder, true
212 m.response = response
213 m.cursorx = Count(placeholder)
217 var suggestions []string
222 switch e := event.(type) {
223 case *tcell.EventKey:
225 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
227 m.AddLog("\t--> (cancel)")
230 // User is done entering their response
231 m.AddLog("\t--> " + m.response)
233 response, canceled = m.response, false
234 m.history[historyType][len(m.history[historyType])-1] = response
236 args := SplitCommandArgs(m.response)
237 currentArgNum := len(args) - 1
238 currentArg := args[currentArgNum]
239 var completionType Completion
241 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
242 if command, ok := commands[args[0]]; ok {
243 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
247 if currentArgNum >= len(completionTypes) {
248 completionType = completionTypes[len(completionTypes)-1]
250 completionType = completionTypes[currentArgNum]
254 if completionType == FileCompletion {
255 chosen, suggestions = FileComplete(currentArg)
256 } else if completionType == CommandCompletion {
257 chosen, suggestions = CommandComplete(currentArg)
258 } else if completionType == HelpCompletion {
259 chosen, suggestions = HelpComplete(currentArg)
260 } else if completionType == OptionCompletion {
261 chosen, suggestions = OptionComplete(currentArg)
262 } else if completionType == PluginCmdCompletion {
263 chosen, suggestions = PluginCmdComplete(currentArg)
264 } else if completionType == PluginNameCompletion {
265 chosen, suggestions = PluginNameComplete(currentArg)
266 } else if completionType < NoCompletion {
267 chosen, suggestions = PluginComplete(completionType, currentArg)
270 if len(suggestions) > 1 {
271 chosen = chosen + CommonSubstring(suggestions...)
275 m.response = JoinCommandArgs(append(args[:len(args)-1], chosen)...)
276 m.cursorx = Count(m.response)
281 m.HandleEvent(event, m.history[historyType])
284 for _, v := range tabs[curTab].views {
289 if len(suggestions) > 1 {
290 m.DisplaySuggestions(suggestions)
297 return response, canceled
300 // HandleEvent handles an event for the prompter
301 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
302 switch e := event.(type) {
303 case *tcell.EventKey:
304 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
305 for key, actions := range bindings {
306 if e.Key() == key.keyCode {
307 if e.Key() == tcell.KeyRune {
308 if e.Rune() != key.r {
312 if e.Modifiers() == key.modifiers {
313 for _, action := range actions {
314 funcName := FuncName(action)
316 case "main.(*View).CursorUp":
317 if m.historyNum > 0 {
319 m.response = history[m.historyNum]
320 m.cursorx = Count(m.response)
322 case "main.(*View).CursorDown":
323 if m.historyNum < len(history)-1 {
325 m.response = history[m.historyNum]
326 m.cursorx = Count(m.response)
328 case "main.(*View).CursorLeft":
332 case "main.(*View).CursorRight":
333 if m.cursorx < Count(m.response) {
336 case "main.(*View).CursorStart", "main.(*View).StartOfLine":
338 case "main.(*View).CursorEnd", "main.(*View).EndOfLine":
339 m.cursorx = Count(m.response)
340 case "main.(*View).Backspace":
342 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
345 case "main.(*View).Paste":
346 clip, _ := clipboard.ReadAll("clipboard")
347 m.response = Insert(m.response, m.cursorx, clip)
348 m.cursorx += Count(clip)
357 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
360 history[m.historyNum] = m.response
362 case *tcell.EventPaste:
364 m.response = Insert(m.response, m.cursorx, clip)
365 m.cursorx += Count(clip)
366 case *tcell.EventMouse:
368 x -= Count(m.message)
369 button := e.Buttons()
370 _, screenH := screen.Size()
378 } else if m.cursorx > Count(m.response) {
379 m.cursorx = Count(m.response)
386 // Reset resets the messenger's cursor, message and response
387 func (m *Messenger) Reset() {
393 // Clear clears the line at the bottom of the editor
394 func (m *Messenger) Clear() {
395 w, h := screen.Size()
396 for x := 0; x < w; x++ {
397 screen.SetContent(x, h-1, ' ', nil, defStyle)
401 func (m *Messenger) DisplaySuggestions(suggestions []string) {
402 w, screenH := screen.Size()
406 statusLineStyle := defStyle.Reverse(true)
407 if style, ok := colorscheme["statusline"]; ok {
408 statusLineStyle = style
411 for x := 0; x < w; x++ {
412 screen.SetContent(x, y, ' ', nil, statusLineStyle)
416 for _, suggestion := range suggestions {
417 for _, c := range suggestion {
418 screen.SetContent(x, y, c, nil, statusLineStyle)
421 screen.SetContent(x, y, ' ', nil, statusLineStyle)
426 // Display displays messages or prompts
427 func (m *Messenger) Display() {
428 _, h := screen.Size()
430 if m.hasPrompt || globalSettings["infobar"].(bool) {
431 runes := []rune(m.message + m.response)
432 for x := 0; x < len(runes); x++ {
433 screen.SetContent(x, h-1, runes[x], nil, m.style)
439 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
444 // A GutterMessage is a message displayed on the side of the editor
445 type GutterMessage struct {
451 // These are the different types of messages
453 // GutterInfo represents a simple info message
455 // GutterWarning represents a compiler warning
457 // GutterError represents a compiler error