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
126 // if len(tabs) > 1 {
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 func (v *View) HSplit() bool {
223 v.Resize(screen.Size())
225 newView := NewViewWidthHeight(NewBuffer([]byte{}, ""), v.widthPercent, v.heightPercent)
226 newView.TabNum = v.TabNum
227 newView.y = v.y + v.height + 1
229 tab := tabs[v.TabNum]
231 newView.Num = len(tab.views)
232 tab.views = append(tab.views, newView)
236 func (v *View) VSplit() bool {
238 v.Resize(screen.Size())
240 newView := NewViewWidthHeight(NewBuffer([]byte{}, ""), v.widthPercent, v.heightPercent)
241 newView.TabNum = v.TabNum
243 newView.x = v.x + v.width
244 tab := tabs[v.TabNum]
246 newView.Num = len(tab.views)
247 tab.views = append(tab.views, newView)
251 // Relocate moves the view window so that the cursor is in view
252 // This is useful if the user has scrolled far away, and then starts typing
253 func (v *View) Relocate() bool {
256 scrollmargin := int(settings["scrollmargin"].(float64))
257 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
258 v.Topline = cy - scrollmargin
260 } else if cy < v.Topline {
264 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
265 v.Topline = cy - v.height + 1 + scrollmargin
267 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
268 v.Topline = v.Buf.NumLines - v.height
272 cx := v.Cursor.GetVisualX()
277 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
278 v.leftCol = cx - v.width + v.lineNumOffset + 1
284 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
286 func (v *View) MoveToMouseClick(x, y int) {
287 if y-v.Topline > v.height-1 {
289 y = v.height + v.Topline - 1
291 if y >= v.Buf.NumLines {
292 y = v.Buf.NumLines - 1
301 x = v.Cursor.GetCharPosInLine(y, x)
302 if x > Count(v.Buf.Line(y)) {
303 x = Count(v.Buf.Line(y))
307 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
310 // HandleEvent handles an event passed by the main loop
311 func (v *View) HandleEvent(event tcell.Event) {
312 // This bool determines whether the view is relocated at the end of the function
313 // By default it's true because most events should cause a relocate
318 switch e := event.(type) {
319 case *tcell.EventResize:
322 case *tcell.EventKey:
323 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
324 // Insert a character
325 if v.Cursor.HasSelection() {
326 v.Cursor.DeleteSelection()
327 v.Cursor.ResetSelection()
329 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
332 for _, pl := range loadedPlugins {
333 err := Call(pl+".onRune", []string{string(e.Rune())})
334 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
339 for key, actions := range bindings {
340 if e.Key() == key.keyCode {
341 if e.Key() == tcell.KeyRune {
342 if e.Rune() != key.r {
346 if e.Modifiers() == key.modifiers {
348 for _, action := range actions {
349 relocate = action(v) || relocate
350 for _, pl := range loadedPlugins {
351 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
352 err := Call(pl+".on"+funcName[len(funcName)-1], nil)
353 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
362 case *tcell.EventPaste:
363 if v.Cursor.HasSelection() {
364 v.Cursor.DeleteSelection()
365 v.Cursor.ResetSelection()
368 v.Buf.Insert(v.Cursor.Loc, clip)
369 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
371 case *tcell.EventMouse:
373 x -= v.lineNumOffset - v.leftCol + v.x
375 // Don't relocate for mouse events
378 button := e.Buttons()
384 v.MoveToMouseClick(x, y)
385 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
388 v.lastClickTime = time.Now()
391 v.doubleClick = false
393 v.Cursor.SelectLine()
396 v.lastClickTime = time.Now()
399 v.tripleClick = false
401 v.Cursor.SelectWord()
404 v.doubleClick = false
405 v.tripleClick = false
406 v.lastClickTime = time.Now()
408 v.Cursor.OrigSelection[0] = v.Cursor.Loc
409 v.Cursor.CurSelection[0] = v.Cursor.Loc
410 v.Cursor.CurSelection[1] = v.Cursor.Loc
412 v.mouseReleased = false
413 } else if !v.mouseReleased {
414 v.MoveToMouseClick(x, y)
416 v.Cursor.AddLineToSelection()
417 } else if v.doubleClick {
418 v.Cursor.AddWordToSelection()
420 v.Cursor.CurSelection[1] = v.Cursor.Loc
423 case tcell.ButtonNone:
424 // Mouse event with no click
425 if !v.mouseReleased {
426 // Mouse was just released
428 // Relocating here isn't really necessary because the cursor will
429 // be in the right place from the last mouse event
430 // However, if we are running in a terminal that doesn't support mouse motion
431 // events, this still allows the user to make selections, except only after they
434 if !v.doubleClick && !v.tripleClick {
435 v.MoveToMouseClick(x, y)
436 v.Cursor.CurSelection[1] = v.Cursor.Loc
438 v.mouseReleased = true
442 scrollspeed := int(settings["scrollspeed"].(float64))
443 v.ScrollUp(scrollspeed)
444 case tcell.WheelDown:
446 scrollspeed := int(settings["scrollspeed"].(float64))
447 v.ScrollDown(scrollspeed)
454 if settings["syntax"].(bool) {
459 // GutterMessage creates a message in this view's gutter
460 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
462 gutterMsg := GutterMessage{
467 for _, v := range v.messages {
468 for _, gmsg := range v {
469 if gmsg.lineNum == lineN {
474 messages := v.messages[section]
475 v.messages[section] = append(messages, gutterMsg)
478 // ClearGutterMessages clears all gutter messages from a given section
479 func (v *View) ClearGutterMessages(section string) {
480 v.messages[section] = []GutterMessage{}
483 // ClearAllGutterMessages clears all the gutter messages
484 func (v *View) ClearAllGutterMessages() {
485 for k := range v.messages {
486 v.messages[k] = []GutterMessage{}
490 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
491 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
492 screen.SetContent(x, y, ch, combc, style)
496 // DisplayView renders the view to the screen
497 func (v *View) DisplayView() {
499 // The character number of the character in the top left of the screen
500 charNum := Loc{0, v.Topline}
502 // Convert the length of buffer to a string, and get the length of the string
503 // We are going to have to offset by that amount
504 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
505 // + 1 for the little space after the line number
506 if settings["ruler"] == true {
507 v.lineNumOffset = maxLineLength + 1
511 highlightStyle := defStyle
513 var hasGutterMessages bool
514 for _, v := range v.messages {
516 hasGutterMessages = true
519 if hasGutterMessages {
524 // One space for the extra split divider
528 for lineN := 0; lineN < v.height; lineN++ {
531 // Draw the split divider
532 v.drawCell(x, lineN+v.y, ' ', nil, defStyle.Reverse(true))
535 // If the buffer is smaller than the view height
536 if lineN+v.Topline >= v.Buf.NumLines {
537 // We have to clear all this space
538 for i := x; i < v.x+v.width; i++ {
539 v.drawCell(i, lineN+v.y, ' ', nil, defStyle)
544 line := v.Buf.Line(lineN + v.Topline)
546 if hasGutterMessages {
548 for k := range v.messages {
549 for _, msg := range v.messages[k] {
550 if msg.lineNum == lineN+v.Topline {
552 gutterStyle := defStyle
555 if style, ok := colorscheme["gutter-info"]; ok {
559 if style, ok := colorscheme["gutter-warning"]; ok {
563 if style, ok := colorscheme["gutter-error"]; ok {
567 v.drawCell(x, lineN+v.y, '>', nil, gutterStyle)
569 v.drawCell(x, lineN+v.y, '>', nil, gutterStyle)
571 if v.Cursor.Y == lineN+v.Topline {
572 messenger.Message(msg.msg)
573 messenger.gutterMessage = true
579 v.drawCell(x, lineN+v.y, ' ', nil, defStyle)
581 v.drawCell(x, lineN+v.y, ' ', nil, defStyle)
583 if v.Cursor.Y == lineN+v.Topline && messenger.gutterMessage {
585 messenger.gutterMessage = false
590 // Write the line number
591 lineNumStyle := defStyle
592 if style, ok := colorscheme["line-number"]; ok {
595 // Write the spaces before the line number if necessary
597 if settings["ruler"] == true {
598 lineNum = strconv.Itoa(lineN + v.Topline + 1)
599 for i := 0; i < maxLineLength-len(lineNum); i++ {
600 v.drawCell(x, lineN+v.y, ' ', nil, lineNumStyle)
603 // Write the actual line number
604 for _, ch := range lineNum {
605 v.drawCell(x, lineN+v.y, ch, nil, lineNumStyle)
609 if settings["ruler"] == true {
610 // Write the extra space
611 v.drawCell(x, lineN+v.y, ' ', nil, lineNumStyle)
616 for colN, ch := range line {
617 lineStyle := defStyle
619 if settings["syntax"].(bool) {
620 // Syntax highlighting is enabled
621 highlightStyle = v.matches[lineN][colN]
624 if v.Cursor.HasSelection() &&
625 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
626 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
628 lineStyle = defStyle.Reverse(true)
630 if style, ok := colorscheme["selection"]; ok {
634 lineStyle = highlightStyle
637 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
638 if style, ok := colorscheme["cursor-line"]; ok {
639 fg, _, _ := style.Decompose()
640 lineStyle = lineStyle.Background(fg)
645 lineIndentStyle := defStyle
646 if style, ok := colorscheme["indent-char"]; ok {
647 lineIndentStyle = style
649 if v.Cursor.HasSelection() &&
650 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
651 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
653 lineIndentStyle = defStyle.Reverse(true)
655 if style, ok := colorscheme["selection"]; ok {
656 lineIndentStyle = style
659 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
660 if style, ok := colorscheme["cursor-line"]; ok {
661 fg, _, _ := style.Decompose()
662 lineIndentStyle = lineIndentStyle.Background(fg)
665 indentChar := []rune(settings["indentchar"].(string))
666 if x-v.leftCol >= v.lineNumOffset {
667 v.drawCell(x-v.leftCol, lineN+v.y, indentChar[0], nil, lineIndentStyle)
669 tabSize := int(settings["tabsize"].(float64))
670 for i := 0; i < tabSize-1; i++ {
672 if x-v.leftCol >= v.lineNumOffset {
673 v.drawCell(x-v.leftCol, lineN+v.y, ' ', nil, lineStyle)
676 } else if runewidth.RuneWidth(ch) > 1 {
677 if x-v.leftCol >= v.lineNumOffset {
678 v.drawCell(x-v.leftCol, lineN+v.y, ch, nil, lineStyle)
680 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
682 if x-v.leftCol >= v.lineNumOffset {
683 v.drawCell(x-v.leftCol, lineN+v.y, ' ', nil, lineStyle)
687 if x-v.leftCol >= v.lineNumOffset {
688 v.drawCell(x-v.leftCol, lineN+v.y, ch, nil, lineStyle)
691 charNum = charNum.Move(1, v.Buf)
694 // Here we are at a newline
696 // The newline may be selected, in which case we should draw the selection style
697 // with a space to represent it
698 if v.Cursor.HasSelection() &&
699 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
700 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
702 selectStyle := defStyle.Reverse(true)
704 if style, ok := colorscheme["selection"]; ok {
707 v.drawCell(x-v.leftCol, lineN+v.y, ' ', nil, selectStyle)
711 charNum = charNum.Move(1, v.Buf)
713 for i := 0; i < v.width-((x-v.x)-v.leftCol); i++ {
714 lineStyle := defStyle
715 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
716 if style, ok := colorscheme["cursor-line"]; ok {
717 fg, _, _ := style.Decompose()
718 lineStyle = lineStyle.Background(fg)
721 if !(x-v.leftCol < v.lineNumOffset) {
722 v.drawCell(x+i, lineN+v.y, ' ', nil, lineStyle)
728 // DisplayCursor draws the current buffer's cursor to the screen
729 func (v *View) DisplayCursor() {
730 // Don't draw the cursor if it is out of the viewport or if it has a selection
731 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
734 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
738 // Display renders the view, the cursor, and statusline
739 func (v *View) Display() {
742 if settings["statusline"].(bool) {