Text editors look large because mature editors accumulate decades of features.
The irreducible core is much smaller: wait for a key, change some text, and
draw the result. In this series we will build that core and call it ted–
the tiny editor.
Our first version can open a file, type and delete text, move the cursor, save, and quit. That modest list is important: it is a complete program, not a bag of editor-shaped components.
The terminal is our user interface#
A shell normally collects input until Enter and displays typed characters for
us. An editor needs each key immediately and must draw characters itself. We
use golang.org/x/term to put standard input in raw mode, which means key
presses are delivered directly to our program. We save the old terminal state
first and restore it when the program exits; forgetting this leaves the shell
apparently broken after a crash.
Terminal control codes provide the other half. These are short, standardized
messages that tell a terminal how to draw. For example, \x1b[H moves to the
top-left, \x1b[K clears to the end of a line, and \x1b[7m reverses colors
for the status bar. The drawing code builds the entire screen update before
writing it. That reduces flicker and keeps terminal details out of the code
that manages our text.
The entire application is this loop:
for {
draw()
key := readKey()
if handle(key) { break }
}Special keys arrive as a short sequence of values rather than one value. For
example, an arrow commonly arrives as Escape, [, and A through D.
readKey waits briefly after Escape, then reads a complete control sequence
and turns it into a name such as up or left, so editing code need not
know how the terminal represents keys. The short wait also lets a standalone
Escape key return without blocking the editor.
The buffer stores tabs as tabs; drawing expands each one to the next eight-column stop, and cursor placement uses that same width calculation.
The buffer stores a normalized form of the file. Saving always writes a final newline, including when a newly created file is empty.
Text as an array of lines#
The buffer is simply the editor’s in-memory copy of the text. We represent it
as an array of lines, and each line is an array of characters. In Go the exact
type is [][]rune, but we will normally say “characters” in this post. This
representation makes the three interesting edits visible:
- typing inserts a character into the current line;
- Enter splits one line into two;
- Backspace in column zero joins two lines.
Inserting into the middle of a Go array-like collection shifts the later items, so editing a longer line takes more work than editing a short one. Splitting a line can also shift the lines below it. That is acceptable here. Most lines are short, and transparent code is more valuable than an advanced structure whose benefit we cannot yet observe.
There is one deliberate simplification in our language. Traditional ASCII
stores each character as one small number. UTF-8, which supports writing
systems and symbols from around the world, is more complicated: what a reader
sees as one character can be made from several Unicode values and can occupy a
different amount of screen space. Go calls one decoded Unicode value a
rune. We store those values safely, but call them “characters” in the prose
because that is close enough for this stage. The cursor position is counted in
runes, but the terminal positions it by screen columns. Since a rune can take
zero, one, or two columns – and a visible character can contain several runes –
ted will not place the cursor perfectly for every script or emoji.
Coordinates and state#
Inside the program, the first row and column are numbered zero. Terminals number them starting at one, so only the drawing code adds one. Keeping that conversion in one place avoids counting mistakes.
The viewport is the portion of the file currently visible on screen. We remember its first visible row and adjust it just enough to keep the cursor in view. Redrawing the whole screen after every key is simple and plenty fast for this editor.
The buffer also remembers whether the text has unsaved changes. Programmers
often call this a dirty flag. Saving clears it; edits set it. Quitting with
unsaved changes takes two presses of Ctrl-Q, a tiny safeguard that makes the
program pleasant enough to use on real notes.
Putting the pieces together#
Here is the whole first version as pseudocode – an informal outline that reads like code without requiring exact Go syntax. It leaves out terminal details, but keeps the important boundaries between setup, input, text operations, and drawing:
function main(filename):
buffer = open(filename) or make one empty line
cursor = (row: 0, column: 0)
viewportTop = 0
previousTerminalState = enterRawMode()
defer:
restoreTerminal(previousTerminalState)
clearScreen()
while true:
keep cursor visible by adjusting viewportTop
draw(buffer, cursor, viewportTop)
key = readKey()
if key is a printable character:
insert character at cursor
move cursor right
buffer.dirty = true
else if key is Enter:
split current line at cursor
move cursor to start of new line
buffer.dirty = true
else if key is Backspace:
if cursor is inside a line:
remove character before cursor
else if cursor is not on first line:
join current line to previous line
if text changed:
buffer.dirty = true
else if key is an arrow, Home, End, Page Up, or Page Down:
move cursor, clamped to valid text
else if key is Ctrl-S:
write all lines to filename
buffer.dirty = false
else if key is Ctrl-Q:
if buffer is dirty and this is the first Ctrl-Q:
show "unsaved changes; Ctrl-Q again to quit"
else:
breakDrawing is similarly direct. We repaint every visible row, clear any leftover characters from its previous contents, draw the status bar, and finally place the terminal cursor over the buffer cursor:
function draw(buffer, cursor, viewportTop):
hide terminal cursor
move to top-left
for each terminal row above the status bar:
fileRow = viewportTop + terminalRow
draw buffer.lines[fileRow], or "~" beyond end of file
clear to end of terminal row
draw filename, dirty marker, cursor position, and shortcuts
move terminal cursor to its one-based screen position
show terminal cursor
write the completed frame in one operationThese sketches are intentionally less precise than the program. Their job is
to make the flow visible; main.go, input.go, display.go, and buffer.go
handle key input, tab expansion, valid cursor positions, file errors, and the
exact Go operations. Together, they form a basic but “real” text editor in
about 460 lines of Go, excluding tests.
Try it#
cd ted-part1
go run . ../README.mdUse the arrow keys, Home, End, Tab, Enter, Backspace, and Delete. Save with Ctrl-S
and quit with Ctrl-Q.
This first version has a deliberate omission: once an edit is made, it cannot be taken back. In part 2 we will add undo using the simplest representation that can possibly work, then inspect the price of that simplicity.