diff --git a/editor/draw.go b/editor/draw.go index b04d862..762a5b5 100644 --- a/editor/draw.go +++ b/editor/draw.go @@ -12,6 +12,8 @@ import ( // ---------------------------------------------------------------------------- func (e *editor) RefreshScreen() { + e.scroll() + ab := newBuffer() ab.append(terminal.HideCursor) @@ -25,12 +27,24 @@ func (e *editor) RefreshScreen() { terminal.Write(ab.toString()) } +func (e *editor) scroll() { + if e.cursor.y < e.offset.y { + e.offset.y = e.cursor.y + } + + if e.cursor.y >= e.offset.y + e.screen.Rows { + e.offset.y = e.cursor.y - e.screen.Rows + 1 + } +} + func (e *editor) drawRows(ab *buffer) { for y :=0; y < e.screen.Rows; y++ { - if y >= len(e.rows) { + fileRow := y + e.offset.y + + if fileRow >= len(e.rows) { e.drawPlaceholderRow(y, ab) } else { - row := truncateString(string(e.rows[y].chars), e.screen.Cols) + row := truncateString(string(e.rows[fileRow].chars), e.screen.Cols) ab.append(row) } diff --git a/editor/editor.go b/editor/editor.go index c6f0c93..943dc93 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -11,23 +11,30 @@ import ( // !Editor // ---------------------------------------------------------------------------- -type cursor struct { +type point struct { x int y int } type editor struct { screen *terminal.Screen - cursor *cursor + cursor *point + offset *point rows []*row } func New() *editor { screen := terminal.Size() - cursor := &cursor { 0, 0 } + cursor := &point { 0, 0 } + offset := &point { 0, 0 } var rows []*row - return &editor{screen, cursor, rows } + return &editor{ + screen, + cursor, + offset, + rows, + } } func (e *editor) Open(filename string) { @@ -92,7 +99,7 @@ func (e *editor) moveCursor (key string) { e.cursor.y -= 1 } case keyDown: - if e.cursor.y != e.screen.Rows-1 { + if e.cursor.y < len(e.rows) { e.cursor.y += 1 } case keyPageUp: @@ -106,6 +113,11 @@ func (e *editor) moveCursor (key string) { } } +func (e *editor) appendRow(s string) { + newRow := NewRow(s) + e.rows = append(e.rows, newRow) +} + // Convert the raw ANSI escape sequences to the type of key input func parseEscapeSequence () string { var runes []rune @@ -169,8 +181,3 @@ func parseEscapeSequence () string { return string('\x1b') } - -func (e *editor) appendRow(s string) { - newRow := NewRow(s) - e.rows = append(e.rows, newRow) -} \ No newline at end of file