diff --git a/editor/draw.go b/editor/draw.go index ea57c3e..270cad6 100644 --- a/editor/draw.go +++ b/editor/draw.go @@ -20,7 +20,7 @@ func (e *editor) RefreshScreen() { ab.append(terminal.ResetCursor) e.drawRows(ab) - ab.append(terminal.MoveCursor(e.cursor.x - e.offset.x, e.cursor.y - e.offset.y)) + ab.append(terminal.MoveCursor(e.renderX - e.offset.x, e.cursor.y - e.offset.y)) ab.append(terminal.ShowCursor) @@ -28,6 +28,12 @@ func (e *editor) RefreshScreen() { } func (e *editor) scroll() { + e.renderX = 0 + + if e.cursor.y < e.rowCount() { + e.renderX = e.rows[e.cursor.y].cursorXToRenderX(e.cursor.x) + } + if e.cursor.y < e.offset.y { e.offset.y = e.cursor.y } @@ -36,12 +42,12 @@ func (e *editor) scroll() { e.offset.y = e.cursor.y - e.screen.Rows + 1 } - if e.cursor.x < e.offset.x { - e.offset.x = e.cursor.x + if e.renderX < e.offset.x { + e.offset.x = e.renderX } - if e.cursor.x >= e.offset.x + e.screen.Cols { - e.offset.x = e.cursor.x - e.screen.Cols + if e.renderX >= e.offset.x + e.screen.Cols { + e.offset.x = e.renderX - e.screen.Cols } } @@ -49,7 +55,7 @@ func (e *editor) drawRows(ab *buffer) { for y :=0; y < e.screen.Rows; y++ { fileRow := y + e.offset.y - if fileRow >= len(e.rows) { + if fileRow >= e.rowCount() { e.drawPlaceholderRow(y, ab) } else { rawRow := e.rows[fileRow] @@ -76,7 +82,7 @@ func (e *editor) drawRows(ab *buffer) { } func (e *editor) drawPlaceholderRow(y int, ab *buffer) { - if len(e.rows) == 0 && y == e.screen.Rows / 3 { + if e.rowCount() == 0 && y == e.screen.Rows / 3 { welcome := fmt.Sprintf("Gilo editor -- version %s", KiloVersion) if len(welcome) > e.screen.Cols { welcome = truncateString(welcome, e.screen.Cols) diff --git a/editor/editor.go b/editor/editor.go index 58771cd..735acd7 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -20,6 +20,7 @@ type editor struct { screen *terminal.Screen cursor *point offset *point + renderX int rows []*row } @@ -33,6 +34,7 @@ func New() *editor { screen, cursor, offset, + 0, rows, } } @@ -162,6 +164,10 @@ func (e *editor) appendRow(s string) { e.rows = append(e.rows, newRow) } +func (e *editor) rowCount() int { + return len(e.rows) +} + // Convert the raw ANSI escape sequences to the type of key input func parseEscapeSequence () string { var runes []rune diff --git a/editor/row.go b/editor/row.go index fc3da1e..3725b70 100644 --- a/editor/row.go +++ b/editor/row.go @@ -37,3 +37,17 @@ func (r *row) update() { } } +func (r *row) cursorXToRenderX (cursorX int) int { + renderX := 0 + i := 0 + + for ; i < cursorX; i++ { + if r.chars[i] == '\t' { + renderX += (KiloTabStop - 1) - (renderX % KiloTabStop) + } + + renderX += 1 + } + + return renderX +} \ No newline at end of file