10 "github.com/mattn/go-runewidth"
11 "github.com/zyedidia/tcell"
14 // The View struct stores information about a view into a buffer.
15 // It stores information about the cursor, and the viewport
16 // that the user sees the buffer from.
18 // A pointer to the buffer's cursor for ease of access
21 // The topmost line, used for vertical scrolling
23 // The leftmost column, used for horizontal scrolling
26 // Percentage of the terminal window that this view takes up (from 0 to 100)
30 // Actual with and height
34 // Where this view is located
37 // How much to offset because of line numbers
40 // Holds the list of gutter messages
41 messages map[string][]GutterMessage
43 // Is the help text opened in this view
46 // This is the index of this view in the views array
48 // What tab is this view stored in
51 // Is this view modifiable?
56 // This is the buffer that was last opened
57 // This is used to open help, and then go back to the previously opened buffer
62 // Since tcell doesn't differentiate between a mouse release event
63 // and a mouse move event with no keys pressed, we need to keep
64 // track of whether or not the mouse was pressed (or not released) last event to determine
65 // mouse release events
68 // This stores when the last click was
69 // This is useful for detecting double and triple clicks
70 lastClickTime time.Time
72 // lastCutTime stores when the last ctrl+k was issued.
73 // It is used for clearing the clipboard to replace it with fresh cut lines.
76 // freshClip returns true if the clipboard has never been pasted.
79 // Was the last mouse event actually a double click?
80 // Useful for detecting triple clicks -- if a double click is detected
81 // but the last mouse event was actually a double click, it's a triple click
83 // Same here, just to keep track for mouse move events
86 // Syntax highlighting matches
88 // The matches from the last frame
89 lastMatches SyntaxMatches
92 // NewView returns a new fullscreen view
93 func NewView(buf *Buffer) *View {
94 return NewViewWidthHeight(buf, 100, 100)
97 // NewViewWidthHeight returns a new view with the specified width and height percentages
98 // Note that w and h are percentages not actual values
99 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
106 v.Resize(screen.Size())
110 v.messages = make(map[string][]GutterMessage)
112 v.sline = Statusline{
119 // Resize recalculates the actual width and height of the view from the width and height
121 // This is usually called when the window is resized, or when a split has been added and
122 // the percentages have changed
123 func (v *View) Resize(w, h int) {
124 // Always include 1 line for the command line at the bottom
127 // Include one line for the tab bar at the top
133 v.width = int(float32(w) * float32(v.widthPercent) / 100)
134 // We subtract 1 for the statusline
135 v.height = int(float32(h) * float32(v.heightPercent) / 100)
136 if settings["statusline"].(bool) {
137 // Make room for the status line if it is enabled
142 // ScrollUp scrolls the view up n lines (if possible)
143 func (v *View) ScrollUp(n int) {
144 // Try to scroll by n but if it would overflow, scroll by 1
145 if v.Topline-n >= 0 {
147 } else if v.Topline > 0 {
152 // ScrollDown scrolls the view down n lines (if possible)
153 func (v *View) ScrollDown(n int) {
154 // Try to scroll by n but if it would overflow, scroll by 1
155 if v.Topline+n <= v.Buf.NumLines-v.height {
157 } else if v.Topline < v.Buf.NumLines-v.height {
162 // CanClose returns whether or not the view can be closed
163 // If there are unsaved changes, the user will be asked if the view can be closed
164 // causing them to lose the unsaved changes
165 // The message is what to print after saying "You have unsaved changes. "
166 func (v *View) CanClose(msg string) bool {
167 if v.Buf.IsModified {
168 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
170 if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
172 } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
183 // OpenBuffer opens a new buffer in this view.
184 // This resets the topline, event handler and cursor.
185 func (v *View) OpenBuffer(buf *Buffer) {
189 v.Cursor = &buf.Cursor
192 v.Cursor.ResetSelection()
194 v.messages = make(map[string][]GutterMessage)
198 // Set mouseReleased to true because we assume the mouse is not being pressed when
199 // the editor is opened
200 v.mouseReleased = true
201 v.lastClickTime = time.Time{}
204 // CloseBuffer performs any closing functions on the buffer
205 func (v *View) CloseBuffer() {
211 // ReOpen reloads the current buffer
212 func (v *View) ReOpen() {
213 if v.CanClose("Continue? (yes, no, save) ") {
221 // Relocate moves the view window so that the cursor is in view
222 // This is useful if the user has scrolled far away, and then starts typing
223 func (v *View) Relocate() bool {
226 scrollmargin := int(settings["scrollmargin"].(float64))
227 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
228 v.Topline = cy - scrollmargin
230 } else if cy < v.Topline {
234 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
235 v.Topline = cy - v.height + 1 + scrollmargin
237 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
238 v.Topline = v.Buf.NumLines - v.height
242 cx := v.Cursor.GetVisualX()
247 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
248 v.leftCol = cx - v.width + v.lineNumOffset + 1
254 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
256 func (v *View) MoveToMouseClick(x, y int) {
257 if y-v.Topline > v.height-1 {
259 y = v.height + v.Topline - 1
261 if y >= v.Buf.NumLines {
262 y = v.Buf.NumLines - 1
271 x = v.Cursor.GetCharPosInLine(y, x)
272 if x > Count(v.Buf.Line(y)) {
273 x = Count(v.Buf.Line(y))
277 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
280 // HandleEvent handles an event passed by the main loop
281 func (v *View) HandleEvent(event tcell.Event) {
282 // This bool determines whether the view is relocated at the end of the function
283 // By default it's true because most events should cause a relocate
288 switch e := event.(type) {
289 case *tcell.EventResize:
292 case *tcell.EventKey:
293 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
294 // Insert a character
295 if v.Cursor.HasSelection() {
296 v.Cursor.DeleteSelection()
297 v.Cursor.ResetSelection()
299 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
302 for key, actions := range bindings {
303 if e.Key() == key.keyCode {
304 if e.Key() == tcell.KeyRune {
305 if e.Rune() != key.r {
309 if e.Modifiers() == key.modifiers {
311 for _, action := range actions {
312 relocate = action(v) || relocate
313 for _, pl := range loadedPlugins {
314 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
315 err := Call(pl+"_on"+funcName[len(funcName)-1], nil)
316 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
325 case *tcell.EventPaste:
326 if v.Cursor.HasSelection() {
327 v.Cursor.DeleteSelection()
328 v.Cursor.ResetSelection()
331 v.Buf.Insert(v.Cursor.Loc, clip)
332 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
334 case *tcell.EventMouse:
336 x -= v.lineNumOffset - v.leftCol
338 // Don't relocate for mouse events
341 button := e.Buttons()
347 v.MoveToMouseClick(x, y)
348 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
351 v.lastClickTime = time.Now()
354 v.doubleClick = false
356 v.Cursor.SelectLine()
359 v.lastClickTime = time.Now()
362 v.tripleClick = false
364 v.Cursor.SelectWord()
367 v.doubleClick = false
368 v.tripleClick = false
369 v.lastClickTime = time.Now()
371 v.Cursor.OrigSelection[0] = v.Cursor.Loc
372 v.Cursor.CurSelection[0] = v.Cursor.Loc
373 v.Cursor.CurSelection[1] = v.Cursor.Loc
375 v.mouseReleased = false
376 } else if !v.mouseReleased {
377 v.MoveToMouseClick(x, y)
379 v.Cursor.AddLineToSelection()
380 } else if v.doubleClick {
381 v.Cursor.AddWordToSelection()
383 v.Cursor.CurSelection[1] = v.Cursor.Loc
386 case tcell.ButtonNone:
387 // Mouse event with no click
388 if !v.mouseReleased {
389 // Mouse was just released
391 // Relocating here isn't really necessary because the cursor will
392 // be in the right place from the last mouse event
393 // However, if we are running in a terminal that doesn't support mouse motion
394 // events, this still allows the user to make selections, except only after they
397 if !v.doubleClick && !v.tripleClick {
398 v.MoveToMouseClick(x, y)
399 v.Cursor.CurSelection[1] = v.Cursor.Loc
401 v.mouseReleased = true
405 scrollspeed := int(settings["scrollspeed"].(float64))
406 v.ScrollUp(scrollspeed)
407 case tcell.WheelDown:
409 scrollspeed := int(settings["scrollspeed"].(float64))
410 v.ScrollDown(scrollspeed)
417 if settings["syntax"].(bool) {
422 // GutterMessage creates a message in this view's gutter
423 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
425 gutterMsg := GutterMessage{
430 for _, v := range v.messages {
431 for _, gmsg := range v {
432 if gmsg.lineNum == lineN {
437 messages := v.messages[section]
438 v.messages[section] = append(messages, gutterMsg)
441 // ClearGutterMessages clears all gutter messages from a given section
442 func (v *View) ClearGutterMessages(section string) {
443 v.messages[section] = []GutterMessage{}
446 // ClearAllGutterMessages clears all the gutter messages
447 func (v *View) ClearAllGutterMessages() {
448 for k := range v.messages {
449 v.messages[k] = []GutterMessage{}
453 // DisplayView renders the view to the screen
454 func (v *View) DisplayView() {
455 // The character number of the character in the top left of the screen
456 charNum := Loc{0, v.Topline}
458 // Convert the length of buffer to a string, and get the length of the string
459 // We are going to have to offset by that amount
460 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
461 // + 1 for the little space after the line number
462 if settings["ruler"] == true {
463 v.lineNumOffset = maxLineLength + 1
467 highlightStyle := defStyle
469 var hasGutterMessages bool
470 for _, v := range v.messages {
472 hasGutterMessages = true
475 if hasGutterMessages {
479 for lineN := 0; lineN < v.height; lineN++ {
481 // If the buffer is smaller than the view height
482 if lineN+v.Topline >= v.Buf.NumLines {
483 // We have to clear all this space
484 for i := 0; i < v.width; i++ {
485 screen.SetContent(i, lineN+v.y, ' ', nil, defStyle)
490 line := v.Buf.Line(lineN + v.Topline)
492 if hasGutterMessages {
494 for k := range v.messages {
495 for _, msg := range v.messages[k] {
496 if msg.lineNum == lineN+v.Topline {
498 gutterStyle := defStyle
501 if style, ok := colorscheme["gutter-info"]; ok {
505 if style, ok := colorscheme["gutter-warning"]; ok {
509 if style, ok := colorscheme["gutter-error"]; ok {
513 screen.SetContent(x, lineN+v.y, '>', nil, gutterStyle)
515 screen.SetContent(x, lineN+v.y, '>', nil, gutterStyle)
517 if v.Cursor.Y == lineN+v.Topline {
518 messenger.Message(msg.msg)
519 messenger.gutterMessage = true
525 screen.SetContent(x, lineN+v.y, ' ', nil, defStyle)
527 screen.SetContent(x, lineN+v.y, ' ', nil, defStyle)
529 if v.Cursor.Y == lineN+v.Topline && messenger.gutterMessage {
531 messenger.gutterMessage = false
536 // Write the line number
537 lineNumStyle := defStyle
538 if style, ok := colorscheme["line-number"]; ok {
541 // Write the spaces before the line number if necessary
543 if settings["ruler"] == true {
544 lineNum = strconv.Itoa(lineN + v.Topline + 1)
545 for i := 0; i < maxLineLength-len(lineNum); i++ {
546 screen.SetContent(x, lineN+v.y, ' ', nil, lineNumStyle)
549 // Write the actual line number
550 for _, ch := range lineNum {
551 screen.SetContent(x, lineN+v.y, ch, nil, lineNumStyle)
555 if settings["ruler"] == true {
556 // Write the extra space
557 screen.SetContent(x, lineN+v.y, ' ', nil, lineNumStyle)
562 for colN, ch := range line {
563 lineStyle := defStyle
565 if settings["syntax"].(bool) {
566 // Syntax highlighting is enabled
567 highlightStyle = v.matches[lineN][colN]
570 if v.Cursor.HasSelection() &&
571 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
572 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
574 lineStyle = defStyle.Reverse(true)
576 if style, ok := colorscheme["selection"]; ok {
580 lineStyle = highlightStyle
583 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
584 if style, ok := colorscheme["cursor-line"]; ok {
585 fg, _, _ := style.Decompose()
586 lineStyle = lineStyle.Background(fg)
591 lineIndentStyle := defStyle
592 if style, ok := colorscheme["indent-char"]; ok {
593 lineIndentStyle = style
595 if v.Cursor.HasSelection() &&
596 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
597 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
599 lineIndentStyle = defStyle.Reverse(true)
601 if style, ok := colorscheme["selection"]; ok {
602 lineIndentStyle = style
605 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
606 if style, ok := colorscheme["cursor-line"]; ok {
607 fg, _, _ := style.Decompose()
608 lineIndentStyle = lineIndentStyle.Background(fg)
611 indentChar := []rune(settings["indentchar"].(string))
612 if x-v.leftCol >= v.lineNumOffset {
613 screen.SetContent(x-v.leftCol, lineN+v.y, indentChar[0], nil, lineIndentStyle)
615 tabSize := int(settings["tabsize"].(float64))
616 for i := 0; i < tabSize-1; i++ {
618 if x-v.leftCol >= v.lineNumOffset {
619 screen.SetContent(x-v.leftCol, lineN+v.y, ' ', nil, lineStyle)
622 } else if runewidth.RuneWidth(ch) > 1 {
623 if x-v.leftCol >= v.lineNumOffset {
624 screen.SetContent(x-v.leftCol, lineN, ch, nil, lineStyle)
626 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
628 if x-v.leftCol >= v.lineNumOffset {
629 screen.SetContent(x-v.leftCol, lineN, ' ', nil, lineStyle)
633 if x-v.leftCol >= v.lineNumOffset {
634 screen.SetContent(x-v.leftCol, lineN+v.y, ch, nil, lineStyle)
637 charNum = charNum.Move(1, v.Buf)
640 // Here we are at a newline
642 // The newline may be selected, in which case we should draw the selection style
643 // with a space to represent it
644 if v.Cursor.HasSelection() &&
645 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
646 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
648 selectStyle := defStyle.Reverse(true)
650 if style, ok := colorscheme["selection"]; ok {
653 screen.SetContent(x-v.leftCol, lineN+v.y, ' ', nil, selectStyle)
657 charNum = charNum.Move(1, v.Buf)
659 for i := 0; i < v.width-(x-v.leftCol); i++ {
660 lineStyle := defStyle
661 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
662 if style, ok := colorscheme["cursor-line"]; ok {
663 fg, _, _ := style.Decompose()
664 lineStyle = lineStyle.Background(fg)
667 if !(x-v.leftCol < v.lineNumOffset) {
668 screen.SetContent(x+i, lineN+v.y, ' ', nil, lineStyle)
674 // DisplayCursor draws the current buffer's cursor to the screen
675 func (v *View) DisplayCursor() {
676 // Don't draw the cursor if it is out of the viewport or if it has a selection
677 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
680 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
684 // Display renders the view, the cursor, and statusline
685 func (v *View) Display() {
688 if settings["statusline"].(bool) {