11 "github.com/mattn/go-runewidth"
12 "github.com/zyedidia/clipboard"
13 "github.com/zyedidia/micro/cmd/micro/shellwords"
14 "github.com/zyedidia/tcell"
17 // TermMessage sends a message to the user in the terminal. This usually occurs before
18 // micro has been fully initialized -- ie if there is an error in the syntax highlighting
19 // regular expressions
20 // The function must be called when the screen is not initialized
21 // This will write the message, and wait for the user
22 // to press and key to continue
23 func TermMessage(msg ...interface{}) {
24 screenWasNil := screen == nil
31 fmt.Print("\nPress enter to continue")
33 reader := bufio.NewReader(os.Stdin)
34 reader.ReadString('\n')
41 // TermError sends an error to the user in the terminal. Like TermMessage except formatted
43 func TermError(filename string, lineNum int, err string) {
44 TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
47 // Messenger is an object that makes it easy to send messages to the user
48 // and get input from the user
49 type Messenger struct {
51 // Are we currently prompting the user?
53 // Is there a message to print
58 // The user's response to a prompt
60 // style to use when drawing the message
63 // We have to keep track of the cursor for prompting
66 // This map stores the history for all the different kinds of uses Prompt has
67 // It's a map of history type -> history array
68 history map[string][]string
71 // Is the current message a message from the gutter
75 // AddLog sends a message to the log view
76 func (m *Messenger) AddLog(msg ...interface{}) {
77 logMessage := fmt.Sprint(msg...)
78 buffer := m.getBuffer()
79 buffer.insert(buffer.End(), []byte(logMessage+"\n"))
80 buffer.Cursor.Loc = buffer.End()
81 buffer.Cursor.Relocate()
84 func (m *Messenger) getBuffer() *Buffer {
86 m.log = NewBufferFromString("", "")
92 // Message sends a message to the user
93 func (m *Messenger) Message(msg ...interface{}) {
94 displayMessage := fmt.Sprint(msg...)
95 // only display a new message if there isn't an active prompt
96 // this is to prevent overwriting an existing prompt to the user
97 if m.hasPrompt == false {
98 // if there is no active prompt then style and display the message as normal
99 m.message = displayMessage
103 if _, ok := colorscheme["message"]; ok {
104 m.style = colorscheme["message"]
109 // add the message to the log regardless of active prompts
110 m.AddLog(displayMessage)
113 // Error sends an error message to the user
114 func (m *Messenger) Error(msg ...interface{}) {
115 buf := new(bytes.Buffer)
116 fmt.Fprint(buf, msg...)
118 // only display a new message if there isn't an active prompt
119 // this is to prevent overwriting an existing prompt to the user
120 if m.hasPrompt == false {
121 // if there is no active prompt then style and display the message as normal
122 m.message = buf.String()
124 Foreground(tcell.ColorBlack).
125 Background(tcell.ColorMaroon)
127 if _, ok := colorscheme["error-message"]; ok {
128 m.style = colorscheme["error-message"]
132 // add the message to the log regardless of active prompts
133 m.AddLog(buf.String())
136 func (m *Messenger) PromptText(msg ...interface{}) {
137 displayMessage := fmt.Sprint(msg...)
138 // if there is no active prompt then style and display the message as normal
139 m.message = displayMessage
143 if _, ok := colorscheme["message"]; ok {
144 m.style = colorscheme["message"]
148 // add the message to the log regardless of active prompts
149 m.AddLog(displayMessage)
152 // YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
153 func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
157 _, h := screen.Size()
161 screen.ShowCursor(Count(m.message), h-1)
165 switch e := event.(type) {
166 case *tcell.EventKey:
169 if e.Rune() == 'y' || e.Rune() == 'Y' {
173 } else if e.Rune() == 'n' || e.Rune() == 'N' {
178 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
179 m.AddLog("\t--> (cancel)")
189 // LetterPrompt gives the user a prompt and waits for a one letter response
190 func (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {
194 _, h := screen.Size()
198 screen.ShowCursor(Count(m.message), h-1)
202 switch e := event.(type) {
203 case *tcell.EventKey:
206 for _, r := range responses {
208 m.AddLog("\t--> " + string(r))
215 case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
216 m.AddLog("\t--> (cancel)")
226 // Completion represents a type of completion
230 NoCompletion Completion = iota
237 OptionValueCompletion
240 // Prompt sends the user a message and waits for a response to be typed in
241 // This function blocks the main loop while waiting for input
242 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
245 if _, ok := m.history[historyType]; !ok {
246 m.history[historyType] = []string{""}
248 m.history[historyType] = append(m.history[historyType], "")
250 m.historyNum = len(m.history[historyType]) - 1
252 response, canceled := placeholder, true
253 m.response = response
254 m.cursorx = Count(placeholder)
258 var suggestions []string
263 switch e := event.(type) {
264 case *tcell.EventKey:
266 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
268 m.AddLog("\t--> (cancel)")
271 // User is done entering their response
272 m.AddLog("\t--> " + m.response)
274 response, canceled = m.response, false
275 m.history[historyType][len(m.history[historyType])-1] = response
277 args, err := shellwords.Split(m.response)
284 currentArgNum = len(args) - 1
285 currentArg = args[currentArgNum]
287 var completionType Completion
289 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
290 if command, ok := commands[args[0]]; ok {
291 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
295 if currentArgNum >= len(completionTypes) {
296 completionType = completionTypes[len(completionTypes)-1]
298 completionType = completionTypes[currentArgNum]
302 if completionType == FileCompletion {
303 chosen, suggestions = FileComplete(currentArg)
304 } else if completionType == CommandCompletion {
305 chosen, suggestions = CommandComplete(currentArg)
306 } else if completionType == HelpCompletion {
307 chosen, suggestions = HelpComplete(currentArg)
308 } else if completionType == OptionCompletion {
309 chosen, suggestions = OptionComplete(currentArg)
310 } else if completionType == OptionValueCompletion {
311 if currentArgNum-1 > 0 {
312 chosen, suggestions = OptionValueComplete(args[currentArgNum-1], currentArg)
314 } else if completionType == PluginCmdCompletion {
315 chosen, suggestions = PluginCmdComplete(currentArg)
316 } else if completionType == PluginNameCompletion {
317 chosen, suggestions = PluginNameComplete(currentArg)
318 } else if completionType < NoCompletion {
319 chosen, suggestions = PluginComplete(completionType, currentArg)
322 if len(suggestions) > 1 {
323 chosen = chosen + CommonSubstring(suggestions...)
326 if len(suggestions) != 0 {
327 m.response = shellwords.Join(append(args[:len(args)-1], chosen)...)
328 m.cursorx = Count(m.response)
333 m.HandleEvent(event, m.history[historyType])
336 for _, v := range tabs[curTab].views {
341 if len(suggestions) > 1 {
342 m.DisplaySuggestions(suggestions)
349 return response, canceled
352 // UpHistory fetches the previous item in the history
353 func (m *Messenger) UpHistory(history []string) {
354 if m.historyNum > 0 {
356 m.response = history[m.historyNum]
357 m.cursorx = Count(m.response)
361 // DownHistory fetches the next item in the history
362 func (m *Messenger) DownHistory(history []string) {
363 if m.historyNum < len(history)-1 {
365 m.response = history[m.historyNum]
366 m.cursorx = Count(m.response)
370 // CursorLeft moves the cursor one character left
371 func (m *Messenger) CursorLeft() {
377 // CursorRight moves the cursor one character right
378 func (m *Messenger) CursorRight() {
379 if m.cursorx < Count(m.response) {
384 // Start moves the cursor to the start of the line
385 func (m *Messenger) Start() {
389 // End moves the cursor to the end of the line
390 func (m *Messenger) End() {
391 m.cursorx = Count(m.response)
394 // Backspace deletes one character
395 func (m *Messenger) Backspace() {
397 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
402 // Paste pastes the clipboard
403 func (m *Messenger) Paste() {
404 clip, _ := clipboard.ReadAll("clipboard")
405 m.response = Insert(m.response, m.cursorx, clip)
406 m.cursorx += Count(clip)
409 // WordLeft moves the cursor one word to the left
410 func (m *Messenger) WordLeft() {
411 response := []rune(m.response)
416 for IsWhitespace(response[m.cursorx]) {
423 for IsWordChar(string(response[m.cursorx])) {
432 // WordRight moves the cursor one word to the right
433 func (m *Messenger) WordRight() {
434 response := []rune(m.response)
435 if m.cursorx >= len(response) {
438 for IsWhitespace(response[m.cursorx]) {
440 if m.cursorx >= len(response) {
446 if m.cursorx >= len(response) {
449 for IsWordChar(string(response[m.cursorx])) {
451 if m.cursorx >= len(response) {
457 // DeleteWordLeft deletes one word to the left
458 func (m *Messenger) DeleteWordLeft() {
460 m.response = string([]rune(m.response)[:m.cursorx])
463 // HandleEvent handles an event for the prompter
464 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
465 switch e := event.(type) {
466 case *tcell.EventKey:
475 m.DownHistory(history)
477 if e.Modifiers() == tcell.ModCtrl {
479 } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
485 if e.Modifiers() == tcell.ModCtrl {
487 } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
492 case tcell.KeyBackspace2, tcell.KeyBackspace:
493 if e.Modifiers() == tcell.ModCtrl || e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
507 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
510 history[m.historyNum] = m.response
512 case *tcell.EventPaste:
514 m.response = Insert(m.response, m.cursorx, clip)
515 m.cursorx += Count(clip)
516 case *tcell.EventMouse:
518 x -= Count(m.message)
519 button := e.Buttons()
520 _, screenH := screen.Size()
528 } else if m.cursorx > Count(m.response) {
529 m.cursorx = Count(m.response)
536 // Reset resets the messenger's cursor, message and response
537 func (m *Messenger) Reset() {
543 // Clear clears the line at the bottom of the editor
544 func (m *Messenger) Clear() {
545 w, h := screen.Size()
546 for x := 0; x < w; x++ {
547 screen.SetContent(x, h-1, ' ', nil, defStyle)
551 func (m *Messenger) DisplaySuggestions(suggestions []string) {
552 w, screenH := screen.Size()
556 statusLineStyle := defStyle.Reverse(true)
557 if style, ok := colorscheme["statusline"]; ok {
558 statusLineStyle = style
561 for x := 0; x < w; x++ {
562 screen.SetContent(x, y, ' ', nil, statusLineStyle)
566 for _, suggestion := range suggestions {
567 for _, c := range suggestion {
568 screen.SetContent(x, y, c, nil, statusLineStyle)
571 screen.SetContent(x, y, ' ', nil, statusLineStyle)
576 // Display displays messages or prompts
577 func (m *Messenger) Display() {
578 _, h := screen.Size()
580 if m.hasPrompt || globalSettings["infobar"].(bool) {
581 runes := []rune(m.message + m.response)
583 for x := 0; x < len(runes); x++ {
584 screen.SetContent(posx, h-1, runes[x], nil, m.style)
585 posx += runewidth.RuneWidth(runes[x])
591 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
596 // LoadHistory attempts to load user history from configDir/buffers/history
597 // into the history map
598 // The savehistory option must be on
599 func (m *Messenger) LoadHistory() {
600 if GetGlobalOption("savehistory").(bool) {
601 file, err := os.Open(configDir + "/buffers/history")
602 var decodedMap map[string][]string
604 decoder := gob.NewDecoder(file)
605 err = decoder.Decode(&decodedMap)
609 m.Error("Error loading history:", err)
614 if decodedMap != nil {
615 m.history = decodedMap
617 m.history = make(map[string][]string)
620 m.history = make(map[string][]string)
624 // SaveHistory saves the user's command history to configDir/buffers/history
625 // only if the savehistory option is on
626 func (m *Messenger) SaveHistory() {
627 if GetGlobalOption("savehistory").(bool) {
628 // Don't save history past 100
629 for k, v := range m.history {
631 m.history[k] = v[len(m.history[k])-100:]
635 file, err := os.Create(configDir + "/buffers/history")
637 encoder := gob.NewEncoder(file)
639 err = encoder.Encode(m.history)
641 m.Error("Error saving history:", err)
649 // A GutterMessage is a message displayed on the side of the editor
650 type GutterMessage struct {
656 // These are the different types of messages
658 // GutterInfo represents a simple info message
660 // GutterWarning represents a compiler warning
662 // GutterError represents a compiler error