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)")
229 NoCompletion Completion = iota
236 OptionValueCompletion
239 // Prompt sends the user a message and waits for a response to be typed in
240 // This function blocks the main loop while waiting for input
241 func (m *Messenger) Prompt(prompt, placeholder, historyType string, completionTypes ...Completion) (string, bool) {
244 if _, ok := m.history[historyType]; !ok {
245 m.history[historyType] = []string{""}
247 m.history[historyType] = append(m.history[historyType], "")
249 m.historyNum = len(m.history[historyType]) - 1
251 response, canceled := placeholder, true
252 m.response = response
253 m.cursorx = Count(placeholder)
257 var suggestions []string
262 switch e := event.(type) {
263 case *tcell.EventKey:
265 case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
267 m.AddLog("\t--> (cancel)")
270 // User is done entering their response
271 m.AddLog("\t--> " + m.response)
273 response, canceled = m.response, false
274 m.history[historyType][len(m.history[historyType])-1] = response
276 args, err := shellwords.Split(m.response)
283 currentArgNum = len(args) - 1
284 currentArg = args[currentArgNum]
286 var completionType Completion
288 if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
289 if command, ok := commands[args[0]]; ok {
290 completionTypes = append([]Completion{CommandCompletion}, command.completions...)
294 if currentArgNum >= len(completionTypes) {
295 completionType = completionTypes[len(completionTypes)-1]
297 completionType = completionTypes[currentArgNum]
301 if completionType == FileCompletion {
302 chosen, suggestions = FileComplete(currentArg)
303 } else if completionType == CommandCompletion {
304 chosen, suggestions = CommandComplete(currentArg)
305 } else if completionType == HelpCompletion {
306 chosen, suggestions = HelpComplete(currentArg)
307 } else if completionType == OptionCompletion {
308 chosen, suggestions = OptionComplete(currentArg)
309 } else if completionType == OptionValueCompletion {
310 if currentArgNum-1 > 0 {
311 chosen, suggestions = OptionValueComplete(args[currentArgNum-1], currentArg)
313 } else if completionType == PluginCmdCompletion {
314 chosen, suggestions = PluginCmdComplete(currentArg)
315 } else if completionType == PluginNameCompletion {
316 chosen, suggestions = PluginNameComplete(currentArg)
317 } else if completionType < NoCompletion {
318 chosen, suggestions = PluginComplete(completionType, currentArg)
321 if len(suggestions) > 1 {
322 chosen = chosen + CommonSubstring(suggestions...)
325 if len(suggestions) != 0 {
326 m.response = shellwords.Join(append(args[:len(args)-1], chosen)...)
327 m.cursorx = Count(m.response)
332 m.HandleEvent(event, m.history[historyType])
335 for _, v := range tabs[curTab].views {
340 if len(suggestions) > 1 {
341 m.DisplaySuggestions(suggestions)
348 return response, canceled
351 func (m *Messenger) UpHistory(history []string) {
352 if m.historyNum > 0 {
354 m.response = history[m.historyNum]
355 m.cursorx = Count(m.response)
358 func (m *Messenger) DownHistory(history []string) {
359 if m.historyNum < len(history)-1 {
361 m.response = history[m.historyNum]
362 m.cursorx = Count(m.response)
365 func (m *Messenger) CursorLeft() {
370 func (m *Messenger) CursorRight() {
371 if m.cursorx < Count(m.response) {
375 func (m *Messenger) Start() {
378 func (m *Messenger) End() {
379 m.cursorx = Count(m.response)
381 func (m *Messenger) Backspace() {
383 m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
387 func (m *Messenger) Paste() {
388 clip, _ := clipboard.ReadAll("clipboard")
389 m.response = Insert(m.response, m.cursorx, clip)
390 m.cursorx += Count(clip)
392 func (m *Messenger) WordLeft() {
393 response := []rune(m.response)
398 for IsWhitespace(response[m.cursorx]) {
405 for IsWordChar(string(response[m.cursorx])) {
413 func (m *Messenger) WordRight() {
414 response := []rune(m.response)
415 if m.cursorx >= len(response) {
418 for IsWhitespace(response[m.cursorx]) {
420 if m.cursorx >= len(response) {
426 if m.cursorx >= len(response) {
429 for IsWordChar(string(response[m.cursorx])) {
431 if m.cursorx >= len(response) {
436 func (m *Messenger) DeleteWordLeft() {
438 m.response = string([]rune(m.response)[:m.cursorx])
441 // HandleEvent handles an event for the prompter
442 func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
443 switch e := event.(type) {
444 case *tcell.EventKey:
453 m.DownHistory(history)
455 if e.Modifiers() == tcell.ModCtrl {
457 } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
463 if e.Modifiers() == tcell.ModCtrl {
465 } else if e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
470 case tcell.KeyBackspace2, tcell.KeyBackspace:
471 if e.Modifiers() == tcell.ModCtrl || e.Modifiers() == tcell.ModAlt || e.Modifiers() == tcell.ModMeta {
485 m.response = Insert(m.response, m.cursorx, string(e.Rune()))
488 history[m.historyNum] = m.response
490 case *tcell.EventPaste:
492 m.response = Insert(m.response, m.cursorx, clip)
493 m.cursorx += Count(clip)
494 case *tcell.EventMouse:
496 x -= Count(m.message)
497 button := e.Buttons()
498 _, screenH := screen.Size()
506 } else if m.cursorx > Count(m.response) {
507 m.cursorx = Count(m.response)
514 // Reset resets the messenger's cursor, message and response
515 func (m *Messenger) Reset() {
521 // Clear clears the line at the bottom of the editor
522 func (m *Messenger) Clear() {
523 w, h := screen.Size()
524 for x := 0; x < w; x++ {
525 screen.SetContent(x, h-1, ' ', nil, defStyle)
529 func (m *Messenger) DisplaySuggestions(suggestions []string) {
530 w, screenH := screen.Size()
534 statusLineStyle := defStyle.Reverse(true)
535 if style, ok := colorscheme["statusline"]; ok {
536 statusLineStyle = style
539 for x := 0; x < w; x++ {
540 screen.SetContent(x, y, ' ', nil, statusLineStyle)
544 for _, suggestion := range suggestions {
545 for _, c := range suggestion {
546 screen.SetContent(x, y, c, nil, statusLineStyle)
549 screen.SetContent(x, y, ' ', nil, statusLineStyle)
554 // Display displays messages or prompts
555 func (m *Messenger) Display() {
556 _, h := screen.Size()
558 if m.hasPrompt || globalSettings["infobar"].(bool) {
559 runes := []rune(m.message + m.response)
561 for x := 0; x < len(runes); x++ {
562 screen.SetContent(posx, h-1, runes[x], nil, m.style)
563 posx += runewidth.RuneWidth(runes[x])
569 screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
574 // LoadHistory attempts to load user history from configDir/buffers/history
575 // into the history map
576 // The savehistory option must be on
577 func (m *Messenger) LoadHistory() {
578 if GetGlobalOption("savehistory").(bool) {
579 file, err := os.Open(configDir + "/buffers/history")
580 var decodedMap map[string][]string
582 decoder := gob.NewDecoder(file)
583 err = decoder.Decode(&decodedMap)
587 m.Error("Error loading history:", err)
592 if decodedMap != nil {
593 m.history = decodedMap
595 m.history = make(map[string][]string)
598 m.history = make(map[string][]string)
602 // SaveHistory saves the user's command history to configDir/buffers/history
603 // only if the savehistory option is on
604 func (m *Messenger) SaveHistory() {
605 if GetGlobalOption("savehistory").(bool) {
606 // Don't save history past 100
607 for k, v := range m.history {
609 m.history[k] = v[len(m.history[k])-100:]
613 file, err := os.Create(configDir + "/buffers/history")
615 encoder := gob.NewEncoder(file)
617 err = encoder.Encode(m.history)
619 m.Error("Error saving history:", err)
627 // A GutterMessage is a message displayed on the side of the editor
628 type GutterMessage struct {
634 // These are the different types of messages
636 // GutterInfo represents a simple info message
638 // GutterWarning represents a compiler warning
640 // GutterError represents a compiler error