about summary refs log tree commit diff
path: root/documentation/DOCS.md
diff options
context:
space:
mode:
Diffstat (limited to 'documentation/DOCS.md')
-rw-r--r--documentation/DOCS.md2804
1 files changed, 2804 insertions, 0 deletions
diff --git a/documentation/DOCS.md b/documentation/DOCS.md
new file mode 100644
index 0000000..08c0e65
--- /dev/null
+++ b/documentation/DOCS.md
@@ -0,0 +1,2804 @@
+# Lume Documentation
+
+> **Lume 0.1 Alpha** — This documentation reflects the current alpha release. Behaviours described here are accurate as of this version but may change in future releases.
+
+---
+
+## Introduction
+
+Lume is a terminal text editor written in C and Lua. It is small, fast, and deliberately limited in scope. It provides syntax highlighting, incremental search, multi-buffer editing, a kill ring, and autocompletion — the things that make a terminal editor genuinely comfortable to use — without venturing into the territory of language servers, linters, multi-line syntax analysis, or any other feature that requires the editor to form opinions about what your code means.
+
+That last point is the heart of Lume's design. A great deal of effort in modern editors goes into understanding code at a semantic level — inferring types, resolving symbols, detecting errors before compilation. When this works, it is useful. When it does not, it produces false highlights, spurious warnings, autocorrections that fight you, and an editor that feels like it is constantly second-guessing you. For many languages and many workflows, it does not work reliably enough to be worth the cost. Lume takes the position that an editor's job is to help you write and navigate text, not to interpret it, and that a tool which does less but does it reliably is more useful than one which does more but does it inconsistently.
+
+This does not mean Lume is minimal in the pejorative sense. The editing experience is modelled closely on Emacs — the keybindings, the kill ring, the minibuffer, the buffer model — because that model is exceptionally good for keyboard-driven editing. Lume simply applies that model without the layers of language intelligence that tend to go wrong.
+
+**Philosophy.** The principles that guided Lume's development are:
+
+- Code should be plainly readable without comments.
+- As much logic as possible should live in Lua. C is used only to bridge to system interfaces — ncurses, the filesystem, the terminal — that Lua cannot reach on its own. The editor was designed Lua-first; the C layer was written to satisfy whatever the Lua layer needed.
+- No external Lua libraries. The entire program is self-contained.
+- Keep things simple and modular. Each subsystem should be easy to find, easy to read, and easy to replace.
+- The user should always know what the editor is doing. Every significant action is reported in the status bar.
+
+**Name and origins.** Lume began as LumoEdit, a name that combined *Lu* for Lua with *Lumo* — Proton's AI assistant, a nod to the fact that this program was written with AI assistance. LumoEdit was shortened first to *Lume* for a cleaner binary name, and the name stayed. It suits a program written to be used in candlelight at a terminal.
+
+**Current state.** Lume 0.1 Alpha represents the core of the editor. The major systems — editing, search, buffers, highlighting, autocomplete, undo/redo — are all present and working. There are features that will come in future versions: block editing, improvements to automatic bracket pairing, and interface refinements. None of those are in this release. What is here is stable and complete enough to be used as a daily driver for the kinds of files it supports.
+
+---
+
+## Users
+
+This section describes Lume as it works out of the box. No configuration files, no startup scripts, no modification of the source is assumed. Everything described here is the default behaviour of the editor as shipped.
+
+If you are comfortable reading Lua and want to modify or extend the editor, see the [Developers](#developers) section. The two sections are intended to be read by the same people — most users of Lume will also be its developers, at least in a small way.
+
+### Getting Started
+
+Open Lume from the command line, passing any number of files as arguments:
+
+```sh
+lume
+lume myfile.lua
+lume main.c main.h util.c
+```
+
+With no arguments, Lume opens a single empty buffer. With one or more filenames, each file is opened into its own [buffer](#definitions-buffer). Files that do not yet exist are treated as new files and created on first save.
+
+The interface has three regions: the **gutter** on the left (line numbers), the **text area** in the centre, and the **status bar** at the bottom. The status bar doubles as a minibuffer — it is where prompts, messages, and search input appear. There is no mode indicator because Lume has no modes. Every key either edits text or executes a command.
+
+The column 80 position is marked with a subtle `|` character in the text area as a soft ruler. It does not enforce anything; it is purely visual.
+
+### Keybinds
+
+All keybinds use the following notation throughout this documentation:
+
+| Notation | Meaning |
+|---|---|
+| `C-x` | Hold Control and press `x` |
+| `M-x` | Press Escape, then press `x` |
+| `C-x C-s` | The Control-x prefix chord, followed by Control-s |
+
+The Meta key (`M-`) is entered by pressing and releasing Escape, then pressing the next key. On most terminal emulators, holding Alt will also work, though this depends on your terminal configuration.
+
+#### Navigation
+
+| Keybind | Action |
+|---|---|
+| `C-p` / `↑` | Move up one line |
+| `C-n` / `↓` | Move down one line |
+| `C-b` / `←` | Move left one character |
+| `C-f` / `→` | Move right one character |
+| `M-b` | Move backward one word |
+| `M-f` | Move forward one word |
+| `C-a` / `Home` | Move to start of line — see note below |
+| `C-e` / `End` | Move to end of line |
+| `PgUp` | Move up one screen page |
+| `PgDn` | Move down one screen page |
+| `M-<` | Jump to the top of the file |
+| `M->` | Jump to the bottom of the file |
+| `M-a` | Move to the start of the previous blank-line-delimited paragraph |
+| `M-e` | Move to the start of the next blank-line-delimited paragraph |
+| `M-g` | Prompt for a line number and jump to it |
+| `M-m` | Jump to the bracket matching the one under the cursor |
+| `C-l` | Recentre the view so the cursor line is in the middle of the screen |
+
+**A note on `C-a` / `Home`.** Pressing `C-a` when the cursor is already past the first non-whitespace character moves it to the first non-whitespace character (the indentation point). Pressing it again — or pressing it when the cursor is already at the indentation point — moves it to column zero. This is intentional behaviour, not a quirk. It means you can get to either position with at most two presses, and for indented code you usually want the indentation point, not column zero.
+
+Word movement (`M-b`, `M-f`) moves by alphanumeric word boundaries. The cursor lands at the start or end of a word, skipping over punctuation and whitespace.
+
+#### Editing
+
+| Keybind | Action |
+|---|---|
+| `Backspace` | Delete the character before the cursor — see note below |
+| `C-d` / `Delete` | Delete the character after the cursor |
+| `M-d` | Delete the word after the cursor |
+| `M-Backspace` / `C-w` (no selection) | Delete the word before the cursor |
+| `Tab` | Insert spaces to the next 2-column tab stop, or indent a [selection](#definitions-selection) |
+| `Shift-Tab` | Remove up to 2 spaces of leading indentation from the current line, or dedent a selection |
+| `Enter` | Insert a new line, carrying the current line's leading whitespace forward |
+| `Shift-Enter` | Smart new line — see [Language Support](#language-support) |
+| `M-p` | Move the current line (or selected lines) up one line |
+| `M-n` | Move the current line (or selected lines) down one line |
+| `M-;` | Toggle comment on the current line or selection |
+| `M-c` | Duplicate the current line |
+
+**A note on `Backspace`.** When the cursor is in a position where all text to its left on the line is whitespace, Backspace will delete two spaces at once rather than one. This makes unindenting by hand feel like deleting a tab stop — it is seamless when you are working inside indented blocks. When there is any non-whitespace content to the left of the cursor, Backspace deletes exactly one character (or one multi-byte UTF-8 sequence), as you would expect.
+
+**Auto-pairing.** Typing an opening bracket or quote — `(`, `[`, `{`, or `"` — will automatically insert the matching closing character and leave the cursor between the two. If the cursor is already sitting on the closing character of a pair, typing that character will move the cursor through it rather than inserting a duplicate. This keeps the paired structure intact as you type through it.
+
+#### Selection and the Kill Ring
+
+Lume uses a *kill ring* rather than a simple clipboard. The kill ring is a circular buffer that holds multiple killed (cut) pieces of text. You can cycle through it after pasting to retrieve earlier kills. This is described in detail in [Kill Ring](#definitions-kill-ring).
+
+| Keybind | Action |
+|---|---|
+| `C-Space` | Set the mark at the current cursor position, beginning a selection. Press again to clear the mark |
+| `C-g` | Cancel — clears the mark, dismisses autocomplete, and cancels any pending prefix |
+| `M-w` | Copy the selection to the kill ring without deleting it |
+| `C-k` | Kill (cut) from the cursor to end of line, or kill the entire selection if one is active |
+| `C-w` | Kill the selection if one is active; otherwise delete the word before the cursor |
+| `C-y` | Yank (paste) the most recent kill ring entry at the cursor position |
+| `M-y` | After a yank, cycle to the previous kill ring entry, replacing the just-yanked text |
+| `Tab` (with selection) | Indent all lines in the selection by 2 spaces |
+| `Shift-Tab` (with selection) | Dedent all lines in the selection by up to 2 spaces |
+
+A [selection](#definitions-selection) is the region between the **mark** and the cursor. The mark is set with `C-Space` and remains fixed while you move the cursor. The selected region is highlighted. Most editing commands that affect a region — killing, copying, indenting — operate on the active selection when one exists, and fall back to line-level or character-level behaviour when no selection is active.
+
+`C-y` also synchronises with the system clipboard on paste — if the system clipboard contains something that is not already in the kill ring, it is pushed onto the ring first. This means yanking after copying from another application works as expected.
+
+#### Search
+
+| Keybind | Action |
+|---|---|
+| `C-s` | Begin incremental search forward |
+| `C-s` (during search) | Move to the next match |
+| `C-r` (during search) | Move to the previous match (reverse) |
+| `Enter` (during search) | Confirm and exit search, leaving the cursor at the current match |
+| `C-g` (during search) | Cancel and return the cursor to where it was before searching |
+| `M-%` | Search and replace across the entire buffer |
+| `C-r` (normal mode) | Recursive grep — search across all files in the directory tree |
+
+Search is described fully in [Searching](#searching).
+
+#### Buffers
+
+| Keybind | Action |
+|---|---|
+| `C-x C-f` | Open a file into a new buffer (with tab-completion in the prompt) |
+| `C-x C-s` | Save the current buffer |
+| `C-x C-r` | Revert the current buffer from disk, discarding unsaved changes |
+| `C-x C-k` | Kill (close) the current buffer |
+| `C-x C-b` | Open the buffer picker |
+| `C-]` | Switch to the next buffer |
+| `C-\` | Switch to the previous buffer |
+
+#### Miscellaneous
+
+| Keybind | Action |
+|---|---|
+| `C-/` | Undo |
+| `M-/` | Redo |
+| `M-x` | Evaluate a Lua expression in the minibuffer and display the result |
+| `M-!` | Run a shell command and display the first line of output in the status bar |
+| `C-x C-c` | Quit. Prompts for confirmation if any buffer has unsaved changes |
+
+---
+
+### Language Support
+
+Lume provides syntax highlighting, comment toggling, and (for some languages) smart indentation for a set of built-in languages. All language support is registered through a single interface — [`register_filetype`](#register_filetype) — and can be extended in Lua without touching the C layer. See [Adding a Syntax Highlighter (Basic)](#adding-a-syntax-highlighter-basic) if you want to add support for another language.
+
+An important thing to understand about Lume's highlighter model: highlighting is computed one line at a time with no state carried between lines. This is a deliberate design choice. Multi-line highlighting — tracking whether you are inside a block comment, a heredoc, or a multi-line string — requires the editor to maintain and synchronise parse state with the buffer. That state can drift out of sync when edits happen in the middle of a file, producing incorrect highlighting that is worse than no highlighting at all. Lume avoids this problem entirely by limiting itself to what can be determined from a single line. For most practical code, this is perfectly sufficient. For the exceptions — block comments, multi-line strings — those regions will simply appear uncoloured, which is an honest representation of uncertainty rather than a misleading one.
+
+Language detection happens in two ways: by file extension, and by shebang line. Both are checked when a file is opened, and the file extension takes priority.
+
+#### Lua
+
+**Detected by:** `.lua` extension; `lua` shebang.
+
+**Comment prefix:** `--`
+
+Lua receives the most detailed highlighting of any supported language. Keywords are divided into three semantic categories, each with a distinct colour:
+
+- *Definition keywords* (`function`, `local`) — these introduce names into scope.
+- *Logic keywords* (`if`, `then`, `else`, `elseif`, `end`, `for`, `while`, `do`, `repeat`, `until`, `return`, `break`, `goto`, `in`, `not`, `and`, `or`) — these control flow and boolean logic.
+- *Value keywords* (`true`, `false`, `nil`) — these are literal values.
+
+Additionally, string literals (single and double quoted), numeric literals (including hex), operators and punctuation, and single-line `--` comments are all highlighted.
+
+Lua also has **smart indentation** via `Shift-Enter`. When the cursor is at the end of a line that opens a block — a `function` definition, an `if ... then`, a `for ... do`, a `while ... do`, a `do` statement, a `repeat`, or a table literal opened with `{` — pressing `Shift-Enter` inserts a new indented line and, where appropriate, a closing keyword (`end`, `until`, or `}`) on the line below. For `else` and `elseif`, only the indented line is added (the block is already closed by the outer `if`'s `end`). Regular `Enter` always behaves the same regardless of context: it inserts a new line with the same leading whitespace as the current line.
+
+#### C
+
+**Detected by:** `.c`, `.h`, `.cc`, `.cpp` extensions.
+
+**Comment prefix:** `//`
+
+Highlights: C keywords and type names, string and character literals, numeric literals (including `0x` hex, and suffixes `u`, `U`, `l`, `L`), `//` line comments, and operators and punctuation.
+
+> Block comments (`/* */`) span multiple lines and are not highlighted under Lume's single-line model. Lines inside a block comment will appear in the default text colour.
+
+#### Shell
+
+**Detected by:** `.sh`, `.bash`, `.zsh` extensions; `bash`, `sh`, or `zsh` shebangs.
+
+**Comment prefix:** `#`
+
+Highlights: shell keywords (`if`, `then`, `else`, `fi`, `for`, `while`, `do`, `done`, `case`, `esac`, `function`, `return`, `local`, `export`, `echo`, `exit`, and others), string literals, the `$` sigil, numeric literals, and `#` comments.
+
+#### Adding More
+
+Any language can be added by calling `register_filetype` in `main.lua`. No changes to `main.c` are required. See the [Adding a Syntax Highlighter (Basic)](#adding-a-syntax-highlighter-basic) and [Adding a Syntax Highlighter (Advanced)](#adding-a-syntax-highlighter-advanced) guides for a full walkthrough.
+
+---
+
+### Colour Scheme
+
+Lume uses your terminal's colour palette directly via ncurses colour pairs. It does not embed its own colour values — the exact colours you see depend on your terminal emulator's theme. The numbers below are standard ncurses colour indices (0–15).
+
+All colour pairs use a transparent background (`-1`, i.e. inherit the terminal background) unless otherwise noted. Pairs with a specific background colour are used for interactive highlighting — selected text, search matches, matching brackets, and menu items — to make them visually distinct from the surrounding content.
+
+| Name | Pair | Foreground | Background | Used for |
+|---|---|---|---|---|
+| `KEYWORD` | 2 | 6 | default | General language keywords (C, Shell) |
+| `KEYWORD_DEF` | 13 | 6 | default | Definition keywords (`function`, `local` in Lua) |
+| `KEYWORD_LOGIC` | 14 | 4 | default | Logic/control keywords in Lua |
+| `KEYWORD_VALUE` | 15 | 1 | default | Value literals (`true`, `false`, `nil`) |
+| `STRING` | 3 | 2 | default | String literals |
+| `COMMENT` | 4 | 8 | default | Comments |
+| `NUMBER` | 5 | 9 | default | Numeric literals |
+| `OPERATOR` | 6 | 3 | default | Operators and punctuation |
+| `MATCH_BR` | 7 | 3 | 1 | Bracket under cursor and its matching bracket |
+| `MENU_SEL` | 8 | 0 | 6 | Selected item in the autocomplete menu |
+| `SELECTION` | 9 | 0 | 6 | Active text selection region |
+| `GUTTER` | 10 | 8 | default | Line number gutter |
+| `RULER` | 11 | 8 | default | Column 80 ruler mark |
+| `SEARCH_MATCH` | 12 | 0 | 3 | Search match highlights |
+
+Colour indices 1–9 correspond to the standard ANSI colours: 1 = red, 2 = green, 3 = yellow, 4 = blue, 6 = cyan, 8 = bright black (dark grey), 9 = bright red. These will appear as whatever those slots are set to in your terminal theme.
+
+---
+
+### Autocomplete
+
+Lume provides word-completion that activates automatically as you type. When you have typed at least two characters of a word, Lume searches all open buffers for words that begin with what you have typed and, if it finds any, displays a small popup menu near the cursor. The menu dismisses automatically when you continue typing past a completion or move the cursor.
+
+The completion search collects candidates from three sources, ranked in priority order from highest to lowest:
+
+1. **Keywords of the current filetype.** Language keywords that match the prefix are weighted highest, so that `fun` in a Lua file will offer `function` prominently.
+2. **Words in the current buffer.** Matches from the file you are actively editing rank above matches from other files, on the basis that you are more likely to want a word you have already used in this file.
+3. **Words in other open buffers of the same filetype.** Matches from other buffers of the same language rank lowest.
+
+Within each source, candidates are sorted by frequency — words you have used more often appear higher in the menu. The menu shows up to 8 candidates at a time.
+
+The menu can appear either above or below the cursor, depending on how much screen space is available. The arrow key directions adjust to match: the menu always navigates in a consistent visual direction regardless of which side it is on.
+
+| Keybind | Action |
+|---|---|
+| `Tab` | Accept the currently highlighted completion |
+| `↑` / `C-p` | Move the selection up the menu |
+| `↓` / `C-n` | Move the selection down the menu |
+| `C-g` | Dismiss the completion menu without accepting anything |
+
+Any other key dismisses the menu and processes the key normally — typing a space or a punctuation character, for instance, dismisses the menu and inserts that character.
+
+---
+
+### Searching
+
+#### Incremental Search
+
+Press `C-s` to enter incremental search. As you type, Lume highlights all matches in the buffer and keeps the cursor at the nearest match forward from where you started. The status bar shows the current match index and total count, e.g. `Search: fun [3/12]`.
+
+- Press `C-s` again to advance to the next match.
+- Press `C-r` to step backward to the previous match.
+- Press `Enter` to confirm and leave the cursor at the current match.
+- Press `C-g` to cancel and return the cursor to where it was before you started searching.
+
+Search is **smart-case**: if your search term is entirely lower-case, the search is case-insensitive. If your term contains any upper-case character, the search becomes case-sensitive. This means you can search case-insensitively by default and opt into case-sensitivity simply by capitalising a character.
+
+Matches are highlighted with the `SEARCH_MATCH` colour across the entire buffer while search is active. When you confirm or cancel, the highlights are cleared.
+
+When you confirm a search, the matched region is left as an active [selection](#definitions-selection), which you can then operate on immediately — kill it, copy it, replace it.
+
+#### Recursive Grep
+
+Press `C-r` in normal editing mode to open the recursive grep interface. You will be prompted for a search term in the minibuffer, and Lume will then walk the entire directory tree from the current working directory, searching every file it finds. Results are shown in a full-screen list displaying the filename, line number, and matching line with syntax highlighting applied.
+
+Navigate the results list with `↑`/`↓` or `C-p`/`C-n`. Press `Enter` to jump directly to the matching line, opening the file in a new buffer if it is not already open. Press `C-g` to return to the editor without jumping.
+
+Grep search also uses smart-case.
+
+#### Search and Replace
+
+Press `M-%` to open search and replace. You will be prompted first for the pattern to find, then for the replacement text. Both are plain text — no regular expression syntax. The replacement is applied to every occurrence in the buffer at once, and the number of replacements made is reported in the status bar. The operation is undoable as a single step with `C-/`.
+
+If a selection is active when you press `M-%`, the selected text is used as the default search term.
+
+---
+
+## Developers
+
+This section is the technical reference for Lume's internals. It describes every function, option, and subsystem in the codebase in enough detail that you should be able to understand, modify, and extend any part of the editor after reading it.
+
+Do not be put off by the label. This section is written for the same audience as the Users section — people who use Lume and want to understand how it works. The editor is deliberately transparent. The entire program is two files: `main.lua`, where the editor logic lives, and `main.c`, which provides the system interface. There is no build system beyond a C compiler, no package manager, and no hidden configuration. If you can read Lua, you can read the whole editor.
+
+### Definitions
+
+#### Editor
+
+The *editor* in Lume is a single Lua table, `editor`, that holds all of the state for the currently active editing session. It contains the text of the current buffer (as a table of line strings), cursor position, scroll offsets, undo and redo stacks, the kill ring, search state, autocomplete state, and the list of all open buffers. It also contains all of the editing methods — `editor:insert_char`, `editor:delete_char`, `editor:save`, and so on.
+
+Because Lua tables are reference types, passing `editor` to a function gives that function full access to the entire editor state. Most internal functions take `ed` as their first parameter for this reason.
+
+The `editor` table's initial field values serve as the default options and configuration for the editor. See the [editor option](#option-editor) entry for the full list of fields and their defaults.
+
+The editor is exposed as the global `_G.ed` so that code evaluated through `M-x` can access and modify it at runtime.
+
+#### Buffer
+
+A *buffer* is a self-contained unit of editable text, associated with a filename and a filetype. Each open file corresponds to one buffer. Buffers are stored in the `editor.buffers` table and have the same structure as the editor itself — they hold the line table, cursor position, scroll offset, undo stack, modification flag, and all other per-file state.
+
+Only one buffer is active (displayed and editable) at a time. When you switch buffers, the editor's state is saved into the current buffer's entry in `editor.buffers`, and the new buffer's state is loaded back into the editor. This is done by [`save_editor_to_buffer`](#save_editor_to_buffer) and [`load_buffer_to_editor`](#load_buffer_to_editor).
+
+Buffers are created by [`make_buffer`](#make_buffer). Each buffer carries its own highlighter function, keyword list, indentation completers, and comment prefix — these are set when the buffer is created based on the detected filetype, and remain fixed for the lifetime of the buffer.
+
+#### Selection
+
+A *selection* is the region of text between the **mark** and the cursor. The mark is a fixed position set with `C-Space`. Moving the cursor while the mark is set extends or contracts the selection. The mark and cursor together define an ordered range — it does not matter which is earlier in the file; the selection always covers the text between them.
+
+There are two kinds of selection:
+
+**Normal selections** are set explicitly by the user with `C-Space`. They persist until cleared with `C-g`, until a kill or copy operation consumes them, or until an insert operation replaces their content.
+
+**Ephemeral selections** are created automatically by incremental search (`C-s`). When search finds a match, it sets the mark at the start of the match and moves the cursor to the end, creating a selection covering the match. The `ephemeral` flag on the editor marks this selection as temporary. Any action that is not a search operation — moving the cursor, typing, killing — clears an ephemeral selection automatically via [`clear_ephemeral`](#clear_ephemeral). This allows you to immediately act on a search result (delete it, copy it, overtype it) without having to manually clear the selection first.
+
+The functions [`sel_ordered`](#sel_ordered), [`get_selection_text`](#get_selection_text), [`delete_selection`](#delete_selection), [`indent_selection`](#indent_selection), and [`col_in_selection`](#col_in_selection) form the complete interface for working with selections.
+
+#### Highlighter
+
+A *highlighter* is a Lua function that takes a single line of text as a string and returns a list of *spans* — each span describing a contiguous coloured region of that line. Highlighters are registered per-filetype via [`register_filetype`](#register_filetype) and called during rendering by [`editor:draw`](#editordraw).
+
+The key constraint of Lume's highlighter model is that each call receives exactly one line and returns spans for that line only. No state is passed between calls, and no state is stored between lines. This means the highlighter cannot know whether it is inside a multi-line block comment or a multi-line string. This is intentional: a stateless highlighter is always correct for what it can see, whereas a stateful one can go wrong and then stay wrong for the rest of the file. An un-highlighted comment is better than a file that is half-incorrectly highlighted because an edit on line 40 confused the parser's state.
+
+Spans are produced by calling [`push_span`](#push_span) and converted to a per-byte colour map by [`spans_to_color_map`](#spans_to_color_map) before rendering.
+
+#### Kill Ring
+
+The *kill ring* is a fixed-capacity circular list of text strings that have been killed (cut). It is stored in `editor.kill_ring` with a current-position index in `editor.kill_ring_idx`. The maximum number of entries is controlled by [`KILL_RING_MAX`](#kill_ring_max).
+
+Any operation that removes text intentionally — `C-k`, `C-w`, `M-d`, `M-Backspace` — pushes the removed text onto the kill ring. `C-y` (yank) pastes the most recent entry. `M-y` (yank-pop) replaces the just-yanked text with the previous entry in the ring, cycling backward through the history. This allows you to retrieve any of the last `KILL_RING_MAX` killed strings, not just the most recent one.
+
+The kill ring is also synchronised with the system clipboard. When text is killed, it is written to the clipboard via [`clipboard_write`](#clipboard_write). When yanking, if the system clipboard contains text that is not already the current kill ring entry, it is pushed onto the ring first. This means copying from another application and then pressing `C-y` in Lume works as expected.
+
+#### Autocompletion
+
+Autocompletion in Lume is *word completion*: it finds words in the open buffers that begin with the characters you have already typed. It does not analyse syntax, infer types, or consult an external language server. It is fast, always available, and never wrong in the sense of suggesting something that does not exist somewhere in your working set of files.
+
+The completion state is stored in `editor.ac`. When the field is non-nil, the completion menu is visible. The structure holds the list of candidates, the currently selected index, and the length of the prefix that was typed (needed to compute how much to insert when a completion is accepted). The full mechanism is described under [`ac_build`](#ac_build), [`ac_apply`](#ac_apply), and [`ac_handle`](#ac_handle).
+
+---
+
+### Lua Reference
+
+#### Logging
+
+Lume includes a simple file-based logging system for development. It is disabled by default and has no effect on normal use.
+
+##### Options
+
+---
+
+###### `DEBUG`
+
+**Type:** `boolean` — **Default:** `false`
+
+When `false`, all calls to [`log`](#log) are no-ops and no log file is opened or written. Set to `true` at the top of `main.lua` to enable logging, for example when debugging a new feature.
+
+---
+
+###### `LOG_FILE`
+
+**Type:** `string` — **Default:** `"lume.log"`
+
+The path of the log file. Only used when `DEBUG` is `true`. The file is opened in append mode on the first call to `log`, so multiple sessions accumulate in the same file. If the file cannot be opened, logging silently stops.
+
+---
+
+##### Functions
+
+---
+
+###### `log(msg)`
+
+```lua
+log(msg: any) -> nil
+```
+
+Writes a timestamped log entry to [`LOG_FILE`](#debug). The message is passed through `tostring`, so any Lua value can be logged. The timestamp is in UTC `HH:MM:SS` format.
+
+When [`DEBUG`](#debug) is `false`, this function returns immediately and does nothing. The file handle is opened lazily on the first call and shared for the lifetime of the session, then closed by [`close_log`](#close_log).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `msg` | `any` | The value to log. Passed through `tostring`. |
+
+---
+
+###### `close_log()`
+
+```lua
+close_log() -> nil
+```
+
+Closes the log file handle if it is open. Called unconditionally by [`editor:cleanup`](#editorcleaning) on exit, so that log data is flushed even when the session ends due to an error.
+
+---
+
+#### Unicode
+
+Lume works in UTF-8 throughout. The terminal input (`wget_wch` in ncurses) returns Unicode code points, and all text stored in buffers is UTF-8 encoded. The functions in this section are the foundation of correct cursor movement, display width calculation, and character insertion.
+
+The fundamental challenge with UTF-8 in a text editor is that byte positions and display positions are not the same thing. A single character might occupy 1 to 4 bytes in the string. East Asian characters (CJK, Hangul, etc.) occupy 2 display columns rather than 1. Lume handles both of these correctly at the level of these functions, so that all higher-level code — drawing, cursor movement, selection — can operate on byte offsets without having to reason about encoding directly.
+
+##### Functions
+
+---
+
+###### `utf8_char_head(b)`
+
+```lua
+utf8_char_head(b: integer) -> boolean
+```
+
+Returns `true` if byte `b` is the first byte of a UTF-8 character sequence. A byte is a sequence head if it is less than `0x80` (ASCII) or greater than or equal to `0xC0` (a multi-byte lead byte). Continuation bytes (`0x80`–`0xBF`) return `false`.
+
+This is used by [`byte_prev`](#byte_prev) to walk backward through a UTF-8 string correctly: decrement the byte index until `utf8_char_head` returns `true`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `b` | `integer` | A raw byte value (0–255) |
+
+**Returns:** `true` if `b` is a sequence head, `false` if it is a continuation byte.
+
+---
+
+###### `utf8_char_len(b)`
+
+```lua
+utf8_char_len(b: integer) -> integer
+```
+
+Returns the byte length of the UTF-8 character whose first byte is `b`: 1 for ASCII (`< 0x80`), 1 for invalid continuation bytes (treated defensively), 2 for `0xC0–0xDF`, 3 for `0xE0–0xEF`, and 4 for `0xF0–0xFF`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `b` | `integer` | The first byte of a UTF-8 sequence |
+
+**Returns:** The byte length of the sequence (1–4).
+
+---
+
+###### `utf8_decode_at(s, i)`
+
+```lua
+utf8_decode_at(s: string, i: integer) -> (cp: integer|nil, next_i: integer)
+```
+
+Decodes the UTF-8 character starting at byte position `i` in string `s`. Returns the Unicode code point and the byte position of the start of the next character. If `i` is beyond the end of the string, returns `nil` and `i + 1`.
+
+Missing continuation bytes are substituted with `0x80`, so malformed UTF-8 does not cause an error — it produces a replacement code point and advances past the bad byte.
+
+This is the core iteration primitive used by the drawing code and display-width calculations. A typical forward iteration over a string looks like:
+
+```lua
+local i = 1
+while i <= #s do
+  local cp, next_i = utf8_decode_at(s, i)
+  if not cp then break end
+  -- use cp here
+  i = next_i
+end
+```
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | The string to decode from |
+| `i` | `integer` | Byte index of the start of the character (1-based) |
+
+**Returns:** The code point as an integer, and the byte index of the next character.
+
+---
+
+###### `cp_to_utf8(cp)`
+
+```lua
+cp_to_utf8(cp: integer) -> string
+```
+
+Encodes a Unicode code point as a UTF-8 byte string. Handles the full range (1–4 bytes). Used whenever a character is inserted from keyboard input — `get_wchar` returns a code point, and `cp_to_utf8` converts it to the bytes that are stored in the buffer.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `cp` | `integer` | A Unicode code point |
+
+**Returns:** A 1–4 byte string containing the UTF-8 encoding.
+
+---
+
+###### `cp_display_width(cp)`
+
+```lua
+cp_display_width(cp: integer) -> integer
+```
+
+Returns the number of terminal columns that code point `cp` occupies when displayed. Returns 0 for control characters below `0x20`, 2 for East Asian wide characters (CJK unified ideographs, Hangul, full-width forms, emoji blocks, and others), and 1 for everything else.
+
+The ranges checked for double-width characters are a practical subset of the Unicode standard, covering the character sets most commonly encountered in source code and documentation.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `cp` | `integer` | A Unicode code point |
+
+**Returns:** 0, 1, or 2.
+
+---
+
+###### `line_display_width(line, byte_limit)`
+
+```lua
+line_display_width(line: string, byte_limit: integer|nil) -> integer
+```
+
+Computes the total display width (in terminal columns) of a line string up to — but not including — byte position `byte_limit`. If `byte_limit` is `nil`, the entire line is measured.
+
+Used by the horizontal scroll logic to convert between byte cursor positions and display column positions.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `line` | `string` | A line of text |
+| `byte_limit` | `integer` or `nil` | Stop before this byte index. Pass `nil` to measure the whole string. |
+
+**Returns:** The display width in terminal columns.
+
+---
+
+###### `byte_prev(s, pos)`
+
+```lua
+byte_prev(s: string, pos: integer) -> integer
+```
+
+Returns the byte index of the start of the UTF-8 character immediately before byte position `pos` in string `s`. Walks backward from `pos - 1` until it finds a byte that satisfies [`utf8_char_head`](#utf8_char_head). Returns 0 if already at or before the start.
+
+Note that `pos` here is a 0-based byte offset (the convention used throughout the editor for cursor positions), not a 1-based Lua string index.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | The string |
+| `pos` | `integer` | Current byte offset (0-based) |
+
+**Returns:** The byte offset of the previous character's first byte.
+
+---
+
+###### `byte_next(s, pos)`
+
+```lua
+byte_next(s: string, pos: integer) -> integer
+```
+
+Returns the byte offset of the start of the UTF-8 character immediately after the character at byte offset `pos`. Uses [`utf8_char_len`](#utf8_char_len) to determine how far to advance. Clamps to `#s` at the end of the string.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | The string |
+| `pos` | `integer` | Current byte offset (0-based) |
+
+**Returns:** The byte offset of the next character.
+
+---
+
+###### `wch()`
+
+```lua
+wch() -> integer|nil
+```
+
+Reads one character of input from the terminal by calling the C-side `get_wchar`. Returns the Unicode code point of the key pressed, or `nil` if no input is available or an error occurred. Special keys (arrows, function keys, etc.) return ncurses key codes rather than Unicode code points; these are matched against the constants in [`KEY`](#option-key).
+
+`wch` is the single input primitive used everywhere in Lume. All keyboard handling — the main loop, prompts, the search interface, the buffer picker — calls `wch` to read input.
+
+**Returns:** An integer key code, or `nil` on error.
+
+---
+
+#### Text Handling
+
+Utility functions for working with strings and text content at a level above raw bytes.
+
+##### Functions
+
+---
+
+###### `get_lines(text)`
+
+```lua
+get_lines(text: string) -> table
+```
+
+Splits a string into a table of lines by splitting on `\n`. The trailing newline of the last line is not included as an empty entry. If the result would be an empty table (empty input), a table containing one empty string is returned instead, ensuring that the buffer always contains at least one line.
+
+This is used when loading a file and when splitting pasted text during [`editor:yank`](#editoryank).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `text` | `string` | A multi-line string |
+
+**Returns:** A table of line strings (no newline characters).
+
+---
+
+###### `lines_to_buffer(lines)`
+
+```lua
+lines_to_buffer(lines: table) -> string
+```
+
+Joins a table of line strings back into a single string, inserting `\n` between each line. The inverse of [`get_lines`](#get_lines). Used when saving a buffer to disk via [`editor:save`](#editorsave). Note that `editor:save` appends a final `\n` after calling this function, so the saved file always ends with a newline.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `lines` | `table` | A table of line strings |
+
+**Returns:** A single newline-joined string.
+
+---
+
+###### `leading_spaces(line)`
+
+```lua
+leading_spaces(line: string) -> string
+```
+
+Returns the leading whitespace of `line` — the prefix of spaces and tabs before the first non-whitespace character. Returns an empty string if the line starts with a non-whitespace character or is empty.
+
+Used throughout the editor to carry indentation forward when inserting new lines.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `line` | `string` | A line of text |
+
+**Returns:** The leading whitespace string.
+
+---
+
+###### `trim_left(s)`
+
+```lua
+trim_left(s: string) -> string
+```
+
+Returns `s` with all leading whitespace removed. Used by [`editor:insert_newline_smart`](#editorinsert_newline_smart) to check a line's content against indentation completer patterns, which are written against the trimmed content (e.g. `"^function%s"`, not `"^%s*function%s"`).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | A string |
+
+**Returns:** The string with leading whitespace stripped.
+
+---
+
+###### `escape_pattern(s)`
+
+```lua
+escape_pattern(s: string) -> string
+```
+
+Escapes all Lua pattern special characters in `s` so that the result can be used as a literal string in `string.find` or `string.gsub`. The special characters escaped are: `( ) . % + - * ? [ ] ^ $`.
+
+Used by [`editor:search_replace`](#editorsearch_replace) and [`editor:isearch`](#editorisearch) to treat the user's search input as a plain text string rather than a pattern. Lume's search does not expose pattern syntax to the user.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | A raw search term |
+
+**Returns:** The term with pattern metacharacters escaped.
+
+---
+
+###### `escape_replacement(s)`
+
+```lua
+escape_replacement(s: string) -> string
+```
+
+Escapes `%` characters in a replacement string so that they are treated literally by `string.gsub`. Without this, a replacement string containing `%1` would be interpreted as a capture reference.
+
+Used by [`editor:search_replace`](#editorsearch_replace) alongside [`escape_pattern`](#escape_pattern).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `string` | A raw replacement string |
+
+**Returns:** The string with `%` characters escaped.
+
+---
+
+#### File Handling
+
+Functions for working with the filesystem: path manipulation, directory traversal, and file content search.
+
+##### Functions
+
+---
+
+###### `path_join(a, b)`
+
+```lua
+path_join(a: string, b: string) -> string
+```
+
+Joins two path components, ensuring exactly one `/` between them. Trailing slashes are stripped from `a` and leading slashes from `b` before joining. This is used throughout the file-handling code rather than simple concatenation, to avoid double-slash paths.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `a` | `string` | The left path component (e.g. a directory) |
+| `b` | `string` | The right path component (e.g. a filename) |
+
+**Returns:** The joined path.
+
+---
+
+###### `normalize_path(p)`
+
+```lua
+normalize_path(p: string) -> string
+```
+
+Applies lightweight normalisation to a path string: collapses consecutive slashes (`//` → `/`) and removes a leading `./`. This is not a full path canonicalisation — it does not resolve `..` components or symlinks — but it is enough to ensure that paths entered by the user and paths constructed internally compare equal when they refer to the same file.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `p` | `string` | A file path |
+
+**Returns:** The normalised path.
+
+---
+
+###### `collect_files(dir, results)`
+
+```lua
+collect_files(dir: string, results: table) -> nil
+```
+
+Recursively walks the directory tree rooted at `dir` and appends the path of every regular file found to the `results` table. Directories are traversed in the order `list_dir` returns them. Hidden files and directories (those whose names begin with `.`) are skipped entirely.
+
+This is called by [`editor:recursive_search`](#editorrecursive_search) to build the list of files to search through.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `dir` | `string` | The root directory to walk |
+| `results` | `table` | An existing table to append file paths to |
+
+**Returns:** Nothing. Results are appended to the `results` table in place.
+
+---
+
+###### `search_in_file(path, pattern)`
+
+```lua
+search_in_file(path: string, pattern: string) -> table
+```
+
+Loads the file at `path` and searches every line for occurrences of `pattern` as a plain string. Returns a table of match records, each containing the fields `file` (the path), `line` (1-based line number), `col` (1-based column), and `text` (the full content of the matching line).
+
+If the file cannot be loaded, an empty table is returned silently. If the pattern is entirely lower-case, the search is case-insensitive (smart-case); otherwise it is case-sensitive.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `path` | `string` | Path to the file to search |
+| `pattern` | `string` | The plain-text search term |
+
+**Returns:** A table of match records `{file, line, col, text}`.
+
+---
+
+#### Copy, Paste, and the Kill Ring
+
+These functions implement Lume's kill ring — the multi-entry clipboard that is the core of Emacs-style cut-and-paste.
+
+##### Options
+
+---
+
+###### `KILL_RING_MAX`
+
+**Type:** `integer` — **Default:** `30`
+
+The maximum number of entries the kill ring will hold. When a new entry is pushed and the ring is full, the oldest entry is removed. Increase this if you want a longer history; decrease it to reduce memory use (though kill ring entries are just strings, so the cost is minimal).
+
+---
+
+##### Functions
+
+---
+
+###### `clipboard_write(text)`
+
+```lua
+clipboard_write(text: string) -> nil
+```
+
+Writes `text` to the system clipboard by piping it to `pbcopy`. If `pbcopy` is unavailable (i.e. not on macOS), this silently does nothing. On Linux systems, you may wish to replace this with an `xclip` or `wl-copy` invocation. This is one of the few places where Lume makes a platform assumption.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `text` | `string` | The text to place on the clipboard |
+
+---
+
+###### `clipboard_read()`
+
+```lua
+clipboard_read() -> string
+```
+
+Reads the current system clipboard content by reading from `pbpaste`. Returns an empty string if unavailable. Called during [`editor:yank`](#editoryank) to check whether the clipboard contains something newer than the kill ring's current entry.
+
+**Returns:** The clipboard contents as a string, or `""`.
+
+---
+
+###### `kill_ring_push(ed, text)`
+
+```lua
+kill_ring_push(ed: table, text: string) -> nil
+```
+
+Pushes `text` onto the kill ring. If `text` is empty or identical to the most recent entry, the push is skipped (to avoid duplicates from repeated kills of the same content). If the ring is at capacity, the oldest entry is removed from the front. The current index is updated to point to the new entry. Also calls [`clipboard_write`](#clipboard_write) to synchronise with the system clipboard.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `text` | `string` | The text to push |
+
+---
+
+###### `kill_ring_current(ed)`
+
+```lua
+kill_ring_current(ed: table) -> string|nil
+```
+
+Returns the kill ring entry at the current index, or `nil` if the ring is empty.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** The current kill ring entry, or `nil`.
+
+---
+
+###### `kill_ring_cycle(ed)`
+
+```lua
+kill_ring_cycle(ed: table) -> string|nil
+```
+
+Steps the kill ring index backward by one (wrapping around), and returns the entry at the new index. Used by [`editor:yank_pop`](#editoryank_pop) to implement `M-y`. Returns `nil` if the ring is empty.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** The newly selected kill ring entry, or `nil`.
+
+---
+
+#### Syntax Highlighting
+
+The highlighting subsystem provides the infrastructure for per-filetype syntax highlighting. Individual language highlighters are registered here and called during rendering.
+
+##### Options
+
+---
+
+###### `COLOR`
+
+**Type:** `table` — **Default:** (see below)
+
+A table mapping semantic colour names to ncurses colour pair indices. The values here are the pair numbers passed to `init_pair` and `COLOR_PAIR`. They correspond to the pairs described in the [Colour Scheme](#colour-scheme) section.
+
+```lua
+COLOR = {
+  NORMAL       = 0,
+  KEYWORD      = 2,
+  KEYWORD_DEF  = 13,
+  KEYWORD_LOGIC= 14,
+  KEYWORD_VALUE= 15,
+  STRING       = 3,
+  COMMENT      = 4,
+  NUMBER       = 5,
+  OPERATOR     = 6,
+  MATCH_BR     = 7,
+  MENU_SEL     = 8,
+  SELECTION    = 9,
+  GUTTER       = 10,
+  RULER        = 11,
+  SEARCH_MATCH = 12,
+}
+```
+
+When writing a highlighter, always reference colours by their `COLOR.*` name rather than the raw number, both for clarity and so that future colour reassignments propagate automatically.
+
+---
+
+##### Functions
+
+---
+
+###### `setup_colors()`
+
+```lua
+setup_colors() -> nil
+```
+
+Initialises all ncurses colour pairs by calling [`init_color_pair`](#l_init_color_pair) for each entry in [`COLOR`](#option-color). Called once during [`editor:init`](#editorinit) after ncurses is started. Must be called before any colour rendering takes place.
+
+If you add new colour pairs (for example, when adding a new language with custom colours), add corresponding `init_color_pair` calls here.
+
+---
+
+###### `register_filetype(name, exts, shebangs, kw_table, comment, hl_fn)`
+
+```lua
+register_filetype(
+  name:     string,
+  exts:     table,
+  shebangs: table,
+  kw_table: table,
+  comment:  string,
+  hl_fn:    function
+) -> nil
+```
+
+Registers a new filetype with the highlighting system. After registration, any file whose name matches one of the patterns in `exts`, or whose first line matches one of the patterns in `shebangs`, will have `hl_fn` called on each line during rendering, `kw_table` used for autocomplete keyword candidates, and `comment` used as the prefix for `M-;` comment toggling.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `name` | `string` | A short filetype identifier, e.g. `"lua"`, `"c"`, `"python"` |
+| `exts` | `table` | Lua pattern strings matched against the filename, e.g. `{"%.lua$", "%.luac$"}` |
+| `shebangs` | `table` | Lua pattern strings matched against the first line of the file, e.g. `{"lua$"}`. Pass `{}` if shebang detection is not needed. |
+| `kw_table` | `table` | A set-table of keyword strings: `{["keyword"]=true, ...}`. Used for autocomplete. |
+| `comment` | `string` | The single-line comment prefix for this language, e.g. `"--"` or `"//"`. |
+| `hl_fn` | `function` | A function `(line: string) -> table` that returns a list of spans. See the highlighter [guide](#adding-a-syntax-highlighter-basic). |
+
+---
+
+###### `get_filetype(fn, first_line)`
+
+```lua
+get_filetype(fn: string, first_line: string|nil) -> string|nil
+```
+
+Detects the filetype for a given filename and optional first line. Iterates over all registered filetypes, checking the filename against each registered extension pattern. If no extension match is found and `first_line` is provided, checks shebang patterns. Returns the filetype name string, or `nil` if no match is found.
+
+Extension matching takes priority over shebang matching.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `fn` | `string` | The filename or path |
+| `first_line` | `string` or `nil` | The first line of the file, for shebang detection |
+
+**Returns:** A filetype name string, or `nil`.
+
+---
+
+###### `push_span(t, col, len, color)`
+
+```lua
+push_span(t: table, col: integer, len: integer, color: integer) -> nil
+```
+
+Appends a span to the span list `t`. A span records a coloured region: `col` is the 0-based byte offset of the first character, `len` is the number of bytes, and `color` is a `COLOR.*` value. Spans with `len <= 0` are silently ignored.
+
+This is the only function that highlighter functions should call to produce output. Constructing span tables directly is possible but not necessary.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `t` | `table` | The span list being built (passed as `spans` inside a highlighter) |
+| `col` | `integer` | 0-based byte offset of the span start |
+| `len` | `integer` | Byte length of the span |
+| `color` | `integer` | A `COLOR.*` value |
+
+---
+
+###### `get_highlighter(ft)`
+
+```lua
+get_highlighter(ft: string|nil) -> function|nil
+```
+
+Returns the highlighter function registered for filetype `ft`, or `nil` if none is registered or `ft` is `nil`. Called when creating a new buffer to set the buffer's `highlighter` field.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ft` | `string` or `nil` | A filetype name |
+
+**Returns:** A highlighter function, or `nil`.
+
+---
+
+###### `get_keywords(ft)`
+
+```lua
+get_keywords(ft: string|nil) -> table
+```
+
+Returns a list (not a set) of all keyword strings registered for filetype `ft`. Returns an empty table if `ft` is `nil` or has no registered keywords. Used when creating a buffer to populate the `keywords` field, which is used by [`ac_build`](#ac_build).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ft` | `string` or `nil` | A filetype name |
+
+**Returns:** A table of keyword strings.
+
+---
+
+###### `get_comment_prefix(ft)`
+
+```lua
+get_comment_prefix(ft: string|nil) -> string|nil
+```
+
+Returns the comment prefix string registered for filetype `ft`, or `nil` if none. Used when creating a buffer to set the `comment_prefix` field, which is used by [`editor:toggle_comment`](#editortoggle_comment).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ft` | `string` or `nil` | A filetype name |
+
+**Returns:** A comment prefix string such as `"--"` or `"//"`, or `nil`.
+
+---
+
+###### `spans_to_color_map(spans)`
+
+```lua
+spans_to_color_map(spans: table) -> table
+```
+
+Converts a list of spans (as produced by a highlighter) into a flat table mapping each byte offset to a `COLOR.*` value. If spans overlap, the last one in the list wins for any given byte. The resulting table is indexed by 0-based byte offset and used directly by [`editor:draw`](#editordraw) to look up the colour for each character.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `spans` | `table` | A list of span tables `{col, len, color}` |
+
+**Returns:** A table `{[byte_offset] = COLOR.*}`.
+
+---
+
+#### Indentation and Brackets
+
+##### Options
+
+---
+
+###### `indent_completers`
+
+**Type:** `table` — **Default:** Lua rules only
+
+A table mapping filetype names to lists of *completer rules*. Each rule is a table with three fields:
+
+- `pattern` — a Lua pattern matched against the trimmed content of the current line.
+- `indent` — the additional indentation string to add on the new line.
+- `close` — a string to insert on the line below the new line as a closing delimiter, or `nil` if no closing delimiter is needed.
+
+These rules are consulted by [`editor:insert_newline_smart`](#editorinsert_newline_smart) when `Shift-Enter` is pressed. Rules are checked in order; the first match wins.
+
+To add completers for a new language, add an entry to this table:
+
+```lua
+indent_completers["python"] = {
+  {pattern = ":%s*$", indent = "    ", close = nil},
+}
+```
+
+---
+
+###### `BRACKET_PAIRS`
+
+**Type:** `table`
+
+A table used by [`find_matching_bracket`](#find_matching_bracket) to define which characters are paired brackets and in which direction to search for their match. Each entry maps a bracket character to a table containing the open character, the close character, and the search direction (`1` for forward, `-1` for backward).
+
+```lua
+BRACKET_PAIRS = {
+  ["("] = {open="(", close=")", dir= 1},
+  [")"] = {open="(", close=")", dir=-1},
+  ["["] = {open="[", close="]", dir= 1},
+  ["]"] = {open="[", close="]", dir=-1},
+  ["{"] = {open="{", close="}", dir= 1},
+  ["}"] = {open="{", close="}", dir=-1},
+}
+```
+
+---
+
+##### Functions
+
+---
+
+###### `get_indent_completers(ft)`
+
+```lua
+get_indent_completers(ft: string|nil) -> table
+```
+
+Returns the list of indentation completer rules for filetype `ft`, or an empty table if none are defined. Called when creating a buffer to populate the buffer's `completers` field.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ft` | `string` or `nil` | A filetype name |
+
+**Returns:** A list of completer rule tables, or `{}`.
+
+---
+
+###### `find_matching_bracket(lines, row, col)`
+
+```lua
+find_matching_bracket(lines: table, row: integer, col: integer) -> (integer, integer)|nil
+```
+
+Finds the bracket that matches the bracket character at `(row, col)` in `lines`. `row` and `col` are 0-based. If no bracket character is at that position, or no match is found within the buffer, returns `nil`. Otherwise returns the 0-based `(row, col)` of the matching bracket.
+
+The search walks outward from the starting bracket, counting nesting depth. It terminates when depth reaches zero (match found) or when the start or end of the buffer is reached (no match). The direction of the walk is determined by [`BRACKET_PAIRS`](#bracket_pairs).
+
+The matched bracket pair is highlighted in [`editor:draw`](#editordraw) using `COLOR.MATCH_BR`. `M-m` jumps the cursor to the matching bracket.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `lines` | `table` | The buffer's line table |
+| `row` | `integer` | 0-based row of the bracket character |
+| `col` | `integer` | 0-based byte column of the bracket character |
+
+**Returns:** `(row, col)` of the matching bracket, or `nil` if not found.
+
+---
+
+#### Undo and Redo
+
+Lume implements undo and redo via explicit snapshots. Each snapshot records the complete state of the buffer — all lines and the cursor position — at a given moment. This approach is simple and reliable, at the cost of memory proportional to the number of undo steps times the size of the file. For files of normal size, this cost is negligible.
+
+##### Functions
+
+---
+
+###### `make_snapshot(ed)`
+
+```lua
+make_snapshot(ed: table) -> table
+```
+
+Creates a snapshot of the current buffer state: a shallow copy of the `lines` table (so each line string is shared but the table itself is independent), plus the current `cursor_row` and `cursor_col`. This is stored on the undo or redo stack.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** A snapshot table `{lines, cursor_row, cursor_col}`.
+
+---
+
+###### `push_undo(ed)`
+
+```lua
+push_undo(ed: table) -> nil
+```
+
+Pushes a snapshot of the current state onto the undo stack, and clears the redo stack (since a new edit invalidates any redoable future). If the undo stack exceeds 200 entries, the oldest entry is removed to bound memory use.
+
+Every editing operation that modifies the buffer — character insertion, deletion, paste, search-replace — must call `push_undo` before making its change. This is the invariant that makes undo correct.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+---
+
+###### `pop_undo(ed)`
+
+```lua
+pop_undo(ed: table) -> nil
+```
+
+Restores the most recent undo snapshot. Saves the current state onto the redo stack first. Restores the `lines`, `cursor_row`, and `cursor_col` from the snapshot. Sets `ed.modified = true` and clears any active selection. Reports `"Undo"` in the status bar, or `"Nothing to undo"` if the stack is empty.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+---
+
+###### `pop_redo(ed)`
+
+```lua
+pop_redo(ed: table) -> nil
+```
+
+The counterpart to `pop_undo`. Restores the most recent redo snapshot, saving the current state onto the undo stack. Reports `"Redo"` or `"Nothing to redo"`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+---
+
+#### Selections
+
+##### Functions
+
+---
+
+###### `sel_ordered(ed)`
+
+```lua
+sel_ordered(ed: table) -> table|nil
+```
+
+Returns the current selection as an ordered range `{r1, c1, r2, c2}` where `(r1, c1)` is always the earlier position and `(r2, c2)` the later, regardless of whether the mark or the cursor comes first. Returns `nil` if no mark is set.
+
+All functions that operate on a selection — drawing, killing, copying, indenting — call `sel_ordered` to get the normalised range rather than working with the raw mark and cursor positions directly.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** `{r1, c1, r2, c2}` or `nil`.
+
+---
+
+###### `get_selection_text(ed)`
+
+```lua
+get_selection_text(ed: table) -> string|nil
+```
+
+Returns the text content of the current selection as a string, or `nil` if no selection is active. For single-line selections, returns the substring between the mark and cursor. For multi-line selections, joins the fragments with `\n`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** The selected text, or `nil`.
+
+---
+
+###### `delete_selection(ed)`
+
+```lua
+delete_selection(ed: table) -> nil
+```
+
+Deletes the content of the current selection from the buffer. Calls `push_undo` before modifying. For single-line selections, splices out the selected substring. For multi-line selections, removes all intermediate lines and joins the head and tail of the first and last lines. Moves the cursor to the start of the deleted region, clears the mark, and sets `ed.modified = true`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+---
+
+###### `indent_selection(ed, dedent)`
+
+```lua
+indent_selection(ed: table, dedent: boolean) -> nil
+```
+
+Indents or dedents every line in the current selection. When `dedent` is `false`, prepends two spaces to each line. When `dedent` is `true`, removes up to two leading spaces from each line (using a single `gsub` with count 1, so it removes exactly `"  "` if present and does nothing otherwise). Reports `"Indented"` or `"Dedented"` in the status bar.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `dedent` | `boolean` | `true` to remove indentation, `false` to add |
+
+---
+
+###### `col_in_selection(s, row, col)`
+
+```lua
+col_in_selection(s: table|nil, row: integer, col: integer) -> boolean
+```
+
+Returns `true` if byte position `(row, col)` falls within the ordered selection range `s`. Handles single-line and multi-line selections correctly. Returns `false` if `s` is `nil`.
+
+This is called for every character in every visible line during [`editor:draw`](#editordraw) to determine whether to apply selection highlighting.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `s` | `table` or `nil` | An ordered selection range from `sel_ordered`, or `nil` |
+| `row` | `integer` | 0-based row |
+| `col` | `integer` | 0-based byte column |
+
+**Returns:** `true` if the position is inside the selection.
+
+---
+
+###### `clear_ephemeral(ed)`
+
+```lua
+clear_ephemeral(ed: table) -> nil
+```
+
+Clears the mark and resets `ed.ephemeral` to `false` if `ed.ephemeral` is currently `true`. Called at the start of any editing operation that should dismiss an ephemeral (search-created) selection. Has no effect on normal user-set selections.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+---
+
+#### Buffers
+
+##### Functions
+
+---
+
+###### `make_buffer(filename, lines)`
+
+```lua
+make_buffer(filename: string, lines: table) -> table
+```
+
+Creates and returns a new buffer table with the given filename and line content. Detects the filetype from the filename and first line, and populates all filetype-dependent fields: `highlighter`, `completers`, `keywords`, and `comment_prefix`. All other fields (cursor position, scroll offsets, undo stacks, mark, etc.) are initialised to their defaults.
+
+The returned table has the same structure as the editor itself — it can be saved to and loaded from the editor via `save_editor_to_buffer` and `load_buffer_to_editor`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `filename` | `string` | The file path. May be empty for a new unnamed buffer. |
+| `lines` | `table` | The initial line content. |
+
+**Returns:** A new buffer table.
+
+---
+
+###### `save_editor_to_buffer(ed, buf)`
+
+```lua
+save_editor_to_buffer(ed: table, buf: table) -> nil
+```
+
+Copies all mutable editing state from the active editor into the buffer table `buf`. This is called before switching away from a buffer, so that the buffer's record in `editor.buffers` stays up to date. The fields copied are: `filename`, `filetype`, `lines`, `modified`, `cursor_row`, `cursor_col`, `col_offset`, `scroll_offset`, `mark`, `ephemeral`, `undo_stack`, `redo_stack`, `highlighter`, `completers`, `keywords`, and `comment_prefix`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The active editor state |
+| `buf` | `table` | The buffer table to save into |
+
+---
+
+###### `load_buffer_to_editor(ed, buf)`
+
+```lua
+load_buffer_to_editor(ed: table, buf: table) -> nil
+```
+
+The counterpart to `save_editor_to_buffer`. Copies all fields from `buf` back into the editor, making that buffer active. Called by `editor:switch_to_buffer` after saving the current buffer.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The active editor state |
+| `buf` | `table` | The buffer table to load from |
+
+---
+
+#### User Interaction
+
+The three prompt functions form the minibuffer interface. All of them take over the bottom line of the screen for input and return control to the caller when the user confirms or cancels.
+
+##### Functions
+
+---
+
+###### `yn_prompt(ed, label)`
+
+```lua
+yn_prompt(ed: table, label: string) -> boolean
+```
+
+Displays `label` followed by `" (y/n)"` in the status bar and waits for a single key. Returns `true` if `y` or `Y` is pressed, `false` for any other key. Used for destructive confirmations: quitting with unsaved buffers, reverting a modified file, killing a modified buffer.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state (used for screen dimensions) |
+| `label` | `string` | The prompt text |
+
+**Returns:** `true` if confirmed, `false` otherwise.
+
+---
+
+###### `mini_prompt(ed, label, default)`
+
+```lua
+mini_prompt(ed: table, label: string, default: string|nil) -> string|nil
+```
+
+Displays an interactive text input in the status bar, prefixed with `label`. The user can type freely, use Backspace to delete, and press Enter to confirm or `C-g` to cancel. If `default` is provided, it pre-fills the input field.
+
+Returns the final input string on confirmation, or `nil` on cancellation. The input is trimmed to fit the screen width if it grows longer than the available space.
+
+Used for: go-to-line, search and replace, shell command, `M-x` expression, and the search interface.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `label` | `string` | The prompt label |
+| `default` | `string` or `nil` | Optional pre-filled text |
+
+**Returns:** The input string, or `nil` if cancelled.
+
+---
+
+###### `file_prompt(ed, label)`
+
+```lua
+file_prompt(ed: table, label: string) -> string|nil
+```
+
+A specialised prompt for file paths. Behaves like [`mini_prompt`](#mini_prompt) but adds tab-completion: as the user types, Lume lists the matching filesystem entries in a small popup above the status bar. `Tab` accepts the currently highlighted completion and advances to the next one. `↑` and `↓` navigate the completion list. Backspace updates the completion list as the input shrinks.
+
+Completions are generated by listing the directory that the current input implies, so typing `src/` shows the contents of the `src` directory. Directory entries are shown with a trailing `/` so you can distinguish them from files and continue navigating into them.
+
+Used for `C-x C-f` (open file) and for the save-as prompt in [`editor:save`](#editorsave).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `label` | `string` | The prompt label |
+
+**Returns:** The selected or typed path, or `nil` if cancelled.
+
+---
+
+#### Autocompletion
+
+##### Functions
+
+---
+
+###### `ac_build(ed)`
+
+```lua
+ac_build(ed: table) -> table|nil
+```
+
+Builds the autocomplete candidate list based on the word prefix immediately before the cursor. The prefix is found by scanning backward from the cursor position for a run of `[%a_][%w_]*` characters. If the prefix is shorter than 2 characters, no candidates are built and `nil` is returned.
+
+Candidates are collected from three sources: keywords of the current filetype, words in the current buffer, and words in other open buffers of the same filetype. Within each source, candidates are sorted by frequency (higher frequency = later in the list, so they appear at the top of the menu, which is displayed in reverse). Duplicates between sources are eliminated, with higher-priority sources taking precedence.
+
+Returns a table `{candidates, sel, prefix_len}` where `candidates` is the full list, `sel` is the initially selected index (the last entry, i.e. the top of the menu), and `prefix_len` is the byte length of the matched prefix (needed by [`ac_apply`](#ac_apply)).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+
+**Returns:** An autocomplete state table, or `nil` if no candidates found.
+
+---
+
+###### `ac_apply(ed, ac)`
+
+```lua
+ac_apply(ed: table, ac: table) -> nil
+```
+
+Inserts the suffix of the currently selected completion candidate into the buffer at the cursor position. The suffix is the part of the candidate that comes after the already-typed prefix — for example, if the prefix is `"fun"` and the candidate is `"function"`, the suffix `"ction"` is inserted. The cursor is advanced past the inserted suffix. Sets `ed.modified = true`.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `ac` | `table` | The autocomplete state from `ac_build` |
+
+---
+
+###### `ac_handle(ed, ch)`
+
+```lua
+ac_handle(ed: table, ch: integer) -> boolean
+```
+
+Processes a keypress when the autocomplete menu is visible. Returns `true` if the key was consumed by the autocomplete system (and should not be processed by the main keymap), or `false` if it was not.
+
+Keys handled:
+- `C-g` — dismisses the menu.
+- `↑` / `C-p` — moves the menu selection up (direction-aware: adjusts based on whether the menu is above or below the cursor).
+- `↓` / `C-n` — moves the menu selection down.
+- `Tab` — accepts the current selection via [`ac_apply`](#ac_apply) and dismisses the menu.
+- Any other key — dismisses the menu and returns `false`, so the key is processed normally.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state |
+| `ch` | `integer` | The key code from `wch()` |
+
+**Returns:** `true` if the key was consumed, `false` otherwise.
+
+---
+
+#### Keybinds
+
+##### Options
+
+---
+
+###### `KEY`
+
+**Type:** `table`
+
+A table of named key code constants used throughout the keybind system. These map human-readable names to the integer codes returned by `wch()`. The full table:
+
+```lua
+KEY = {
+  ENTER    = 10,  CR = 13,
+  BS       = 127, BS2 = 8, BS3 = 263,
+  DELETE   = 330,
+  TAB      = 9,   SHIFT_TAB = 353,
+  UP       = 259, DOWN  = 258, LEFT = 260, RIGHT = 261,
+  HOME     = 262, END   = 360,
+  PGUP     = 339, PGDN  = 338,
+  ESC      = 27,
+  CTRL_A=1,  CTRL_B=2,  CTRL_C=3,  CTRL_D=4,  CTRL_E=5,  CTRL_F=6,
+  CTRL_G=7,  CTRL_H=8,  CTRL_K=11, CTRL_L=12, CTRL_N=14, CTRL_P=16,
+  CTRL_R=18, CTRL_S=19, CTRL_W=23, CTRL_X=24, CTRL_Y=25, CTRL_Z=26,
+  CTRL_SLASH=31,     CTRL_SPACE=0,
+  CTRL_RBRACKET=29,  CTRL_BACKSLASH=28,
+}
+```
+
+Backspace has three entries (`BS`, `BS2`, `BS3`) because different terminal emulators send different codes for the Backspace key. All three are mapped to the same action in the keymaps. Similarly, Enter has two entries (`ENTER` and `CR`).
+
+---
+
+##### Functions
+
+---
+
+###### `read_csi()`
+
+```lua
+read_csi() -> string
+```
+
+Reads the bytes of a CSI (Control Sequence Introducer) escape sequence after the initial `ESC [` has been consumed. Reads up to 20 characters and stops when it encounters a terminating byte (a letter in the range `@`–`Z`, or `~`, or `u`). Returns the accumulated sequence as a string (not including the `ESC [`).
+
+Used by the main input loop to parse terminal escape sequences for special keys like `Shift-Enter`.
+
+**Returns:** The CSI sequence body as a string.
+
+---
+
+###### `is_shift_enter(seq)`
+
+```lua
+is_shift_enter(seq: string) -> boolean
+```
+
+Returns `true` if the CSI sequence `seq` represents a Shift-Enter keypress. The sequences checked are `"13;2~"`, `"13;2u"`, and `"27;2;13~"`, which are the three encoding schemes used by different terminals for this key combination.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `seq` | `string` | A CSI sequence body as returned by `read_csi()` |
+
+**Returns:** `true` if the sequence is Shift-Enter.
+
+---
+
+###### `make_keymaps(ed)`
+
+```lua
+make_keymaps(ed: table) -> (table, table, table)
+```
+
+Creates and returns the three keymap tables used by the main editing loop: the main keymap, the Meta keymap, and the `C-x` prefix keymap. Each keymap is a table mapping integer key codes to zero-argument functions (closures over `ed`).
+
+The main keymap handles keys pressed without any prefix. The Meta keymap handles keys pressed after Escape. The `C-x` keymap handles keys pressed after `C-x`.
+
+The separation into three tables makes it straightforward to add, remove, or remap individual keybindings by modifying the tables returned by this function, or by replacing `make_keymaps` entirely. See the [Adding a Keybind](#adding-a-keybind-control) guides for examples.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `ed` | `table` | The editor state, captured by the closures |
+
+**Returns:** `(main_map, meta_map, cx_map)` — three keymap tables.
+
+---
+
+#### Editor
+
+##### Options
+
+---
+
+###### `editor` (default values)
+
+The `editor` table is initialised with the following default values. These serve as the configurable defaults for the editor — changing them before calling `editor:init` will alter the editor's starting behaviour.
+
+| Field | Default | Description |
+|---|---|---|
+| `SCROLL_MARGIN` | `5` | Lines of context kept above and below the cursor when scrolling vertically |
+| `H_SCROLL_MARGIN` | `5` | Columns of context kept to the left and right of the cursor when scrolling horizontally |
+| `GUTTER_WIDTH` | `5` | Width in columns of the line number gutter |
+| `RULER_COL` | `80` | The column at which the vertical ruler `\|` is drawn |
+
+The remaining fields (`lines`, `cursor_row`, `screen_rows`, etc.) are initialised to empty/zero values and are set properly by `editor:init`. They are not intended to be configured directly.
+
+---
+
+##### Functions
+
+---
+
+###### `editor:draw()`
+
+```lua
+editor:draw() -> nil
+```
+
+Renders the entire editor to the terminal. This is the central rendering function, called once per iteration of the main loop before reading the next key.
+
+The drawing sequence is:
+
+1. Calls `resize_terminal()` to handle any pending terminal resize events.
+2. Queries the current terminal dimensions and updates `screen_rows` and `screen_cols`.
+3. Clears the screen.
+4. For each visible line (from `scroll_offset` to `scroll_offset + screen_rows - 2`):
+   a. Draws the gutter (line number), highlighted if it is the cursor row.
+   b. Calls the buffer's highlighter function to get colour spans for the line.
+   c. Builds a per-byte colour map from the spans.
+   d. Overlays search match highlighting and selection highlighting on the colour map.
+   e. Iterates over the line character by character (UTF-8 aware), skipping characters that have scrolled off the left edge (`col_offset`), and drawing each visible character with its assigned colour, selection highlight, cursor highlight, bracket-match highlight, or ruler mark.
+   f. Draws the cursor block at the end of the line if the cursor is past the last character.
+5. Draws the autocomplete popup if `editor.ac` is non-nil.
+6. Draws the status bar: modification flag, buffer count, filename, filetype, selection indicator, status message, and cursor position.
+7. Calls `refresh_screen()` to flush the output to the terminal.
+
+The status message (`ed.status_msg`) is cleared after each draw, so messages set during an operation appear for exactly one frame.
+
+---
+
+###### `editor:adjust_scroll()`
+
+```lua
+editor:adjust_scroll() -> nil
+```
+
+Ensures the cursor is within the visible area vertically. If the cursor row is within `SCROLL_MARGIN` lines of the top of the view, the scroll offset is moved up. If it is within `SCROLL_MARGIN` lines of the bottom, the scroll offset is moved down. The scroll offset is then clamped so the view cannot scroll past the end of the buffer. Calls `adjust_col_scroll` to also handle horizontal scrolling.
+
+---
+
+###### `editor:adjust_col_scroll()`
+
+```lua
+editor:adjust_col_scroll() -> nil
+```
+
+Ensures the cursor is within the visible area horizontally. Uses `line_display_width` to compute the cursor's display column, then adjusts `col_offset` so the cursor stays within `H_SCROLL_MARGIN` display columns of the left and right edges of the text area.
+
+---
+
+###### `editor:recenter()`
+
+```lua
+editor:recenter() -> nil
+```
+
+Resets `scroll_offset` so the cursor row is vertically centred on the screen, and resets `col_offset` to zero (scrolling the view back to the left margin). Bound to `C-l`. Useful when you have scrolled far from the cursor or want to reset the horizontal scroll.
+
+---
+
+###### `editor:_raw_insert(str)`
+
+```lua
+editor:_raw_insert(str: string) -> nil
+```
+
+Inserts `str` at the current cursor position in the current line without any checking, undo recording, or side effects beyond updating the cursor column and setting `modified`. This is the lowest-level insert primitive. It is used internally by `insert_char` and `insert_newline_*` after those functions have handled undo and any higher-level logic. It should not generally be called directly from user code; use `insert_char` or a higher-level method instead.
+
+---
+
+###### `editor:insert_char(str)`
+
+```lua
+editor:insert_char(str: string) -> nil
+```
+
+The main character insertion entry point, called for every printable key press in the main loop. Handles several concerns:
+
+- If a selection is active, the selected text is deleted first (and sent to the kill ring), then `str` is inserted in its place.
+- If `str` is the same as the character immediately to the right of the cursor and that character is a closing bracket or `"`, the cursor is advanced through it rather than inserting a duplicate (auto-pair skip-through).
+- If `str` is `\t`, two spaces are inserted as a tab.
+- If `str` follows non-whitespace content and is a space or punctuation, an undo checkpoint is created (word-boundary undo granularity).
+- `str` is inserted via `_raw_insert`.
+- If `str` is an opening bracket or `"`, the matching closing character is inserted after it (auto-pairing), and the cursor is left between the two.
+
+---
+
+###### `editor:delete_char()`
+
+```lua
+editor:delete_char() -> nil
+```
+
+Deletes the character before the cursor (Backspace behaviour). If a selection is active, deletes the selection instead. Otherwise, clears any ephemeral selection and records an undo checkpoint.
+
+Special case: if all content to the left of the cursor on the current line is whitespace and there are at least two spaces immediately before the cursor, two spaces are deleted at once, simulating tab-stop deletion.
+
+If the cursor is at column zero and not on the first line, the current line is joined to the previous one (the cursor moves to the end of the previous line and the lines are concatenated).
+
+---
+
+###### `editor:delete_forward()`
+
+```lua
+editor:delete_forward() -> nil
+```
+
+Deletes the character after the cursor (Delete key behaviour). If a selection is active, deletes the selection instead. Otherwise, deletes one UTF-8 character forward, or joins the next line if at the end of the current line. Records an undo checkpoint.
+
+---
+
+###### `editor:kill_to_eol()`
+
+```lua
+editor:kill_to_eol() -> nil
+```
+
+Kills text from the cursor to the end of the current line, pushing it onto the kill ring. If the cursor is already at the end of the line, kills the newline itself, joining the current line with the next. Records an undo checkpoint.
+
+This is a sub-operation called by `kill_region` when no selection is active. It is not bound directly — `C-k` calls `kill_region`.
+
+---
+
+###### `editor:kill_region()`
+
+```lua
+editor:kill_region() -> nil
+```
+
+Kills the active selection (if one exists) or calls `kill_to_eol`. The killed text is pushed onto the kill ring. Bound to `C-k`. When a selection is active, this is equivalent to a cut operation.
+
+---
+
+###### `editor:copy_region()`
+
+```lua
+editor:copy_region() -> nil
+```
+
+Copies the active selection to the kill ring without deleting it. Clears the mark after copying. Reports `"Copied N chars"`. Bound to `M-w`. If no selection is active, reports `"No selection"`.
+
+---
+
+###### `editor:delete_word_back()`
+
+```lua
+editor:delete_word_back() -> nil
+```
+
+Deletes the word (or whitespace run) immediately before the cursor, in two passes: first skipping any whitespace, then deleting backward through alphanumeric characters. Records an undo checkpoint. If a selection is active, deletes the selection instead.
+
+---
+
+###### `editor:delete_word_forward()`
+
+```lua
+editor:delete_word_forward() -> nil
+```
+
+Deletes the word immediately after the cursor, skipping non-word characters first, then deleting through alphanumeric characters. Records an undo checkpoint. If a selection is active, deletes the selection instead.
+
+---
+
+###### `editor:insert_newline_simple()`
+
+```lua
+editor:insert_newline_simple() -> nil
+```
+
+Inserts a newline at the cursor position, carrying the leading whitespace of the current line forward onto the new line. The cursor moves to the start of the new line's indented content. This is the behaviour of the regular `Enter` key and does not consult the indentation completers.
+
+---
+
+###### `editor:insert_newline_smart()`
+
+```lua
+editor:insert_newline_smart() -> nil
+```
+
+Inserts a newline with smart indentation, bound to `Shift-Enter`. If the cursor is at or near the end of a line (only whitespace follows it) and the trimmed line content matches one of the current buffer's [`indent_completers`](#indent_completers) patterns, the smart behaviour is applied: a new indented line is inserted, and if the matching rule specifies a `close` string, an additional line with that closing delimiter is inserted below. Otherwise, behaves identically to `insert_newline_simple`.
+
+This is how typing a `function` declaration and pressing `Shift-Enter` in a Lua file will automatically give you an indented body line and an `end` below it.
+
+---
+
+###### `editor:tab_or_indent()`
+
+```lua
+editor:tab_or_indent() -> nil
+```
+
+If a selection is active, indents all lines in the selection by 2 spaces via `indent_selection`. Otherwise, inserts enough spaces to reach the next 2-column tab stop: `2 - (cursor_col % 2)` spaces. This means Tab always results in a cursor at an even column, acting as a 2-space tab.
+
+---
+
+###### `editor:shift_tab()`
+
+```lua
+editor:shift_tab() -> nil
+```
+
+If a selection is active, dedents all lines in the selection. Otherwise, if the current line begins with two spaces, removes them and moves the cursor back by 2 (clamped to zero).
+
+---
+
+###### `editor:yank()`
+
+```lua
+editor:yank() -> nil
+```
+
+Pastes the current kill ring entry at the cursor position. First checks the system clipboard — if it contains text not already in the ring, pushes it onto the ring. Then inserts the current entry's text: single-line kills are inserted inline; multi-line kills are split by `\n` and inserted as multiple lines, with the remaining content of the current line moved to after the last inserted line. Records an undo checkpoint.
+
+Sets `prev_was_yank = true` on the editor so that a subsequent `M-y` knows it can cycle the ring.
+
+---
+
+###### `editor:yank_pop()`
+
+```lua
+editor:yank_pop() -> nil
+```
+
+Replaces the most recently yanked text with the previous entry in the kill ring. Can only be used immediately after `C-y` or another `M-y`. Implemented by popping the most recent undo (which undoes the yank), cycling the ring with `kill_ring_cycle`, then re-applying the yank with the new entry and pushing a fresh undo.
+
+---
+
+###### `editor:toggle_comment()`
+
+```lua
+editor:toggle_comment() -> nil
+```
+
+Toggles comments on the current line or all lines in the active selection. First checks whether all selected lines are already commented (have the comment prefix after leading whitespace). If all are commented, removes the prefix from each. If any line is not commented, adds the prefix to all lines (after their leading whitespace). Reports `"Commented"` or `"Uncommented"`. If the buffer has no `comment_prefix` set (unknown filetype), reports an error instead.
+
+---
+
+###### `editor:move_lines(dir)`
+
+```lua
+editor:move_lines(dir: integer) -> nil
+```
+
+Moves the current line (or all lines in the selection) up or down by one position. `dir` must be `-1` (up) or `1` (down). The cursor row (and the mark row, if a selection is active) is adjusted to follow the moved lines. Bound to `M-p` (up) and `M-n` (down).
+
+| Parameter | Type | Description |
+|---|---|---|
+| `dir` | `integer` | `-1` to move up, `1` to move down |
+
+---
+
+###### `editor:move_cursor(drow, dcol)`
+
+```lua
+editor:move_cursor(drow: integer, dcol: integer) -> nil
+```
+
+Moves the cursor by `drow` rows and `dcol` character positions. Row movement clamps to the buffer extent. Column movement of `±1` uses `byte_next` or `byte_prev` to move by one full UTF-8 character. Column movement of `0` leaves the column unchanged but clamps it to the current line length (needed after a row change, since lines may be of different lengths). Clears ephemeral selections.
+
+---
+
+###### `editor:move_to_line_start()`
+
+```lua
+editor:move_to_line_start() -> nil
+```
+
+Implements the toggle behaviour of `C-a` / `Home`. If the cursor is past the first non-whitespace character, moves it to the indentation point (the first non-whitespace position). If the cursor is already at or before the indentation point, moves it to column zero. This means repeated presses alternate between the two positions.
+
+---
+
+###### `editor:move_to_line_end()`
+
+```lua
+editor:move_to_line_end() -> nil
+```
+
+Moves the cursor to the byte position after the last character of the current line (i.e. `#line`). Clears ephemeral selections.
+
+---
+
+###### `editor:page_up()`
+
+```lua
+editor:page_up() -> nil
+```
+
+Moves the cursor up by `screen_rows - 2` lines (one full page), clamped to the top of the buffer. Calls `adjust_scroll`.
+
+---
+
+###### `editor:page_down()`
+
+```lua
+editor:page_down() -> nil
+```
+
+Moves the cursor down by `screen_rows - 2` lines (one full page), clamped to the bottom of the buffer. Calls `adjust_scroll`.
+
+---
+
+###### `editor:word_forward()`
+
+```lua
+editor:word_forward() -> nil
+```
+
+Moves the cursor forward to the end of the next word. First skips non-alphanumeric characters, then advances through alphanumeric characters, stopping at the first non-alphanumeric character or the end of the line.
+
+---
+
+###### `editor:word_backward()`
+
+```lua
+editor:word_backward() -> nil
+```
+
+Moves the cursor backward to the start of the previous word. First skips non-alphanumeric characters going left, then moves back through alphanumeric characters, stopping at the first non-alphanumeric character or the start of the line.
+
+---
+
+###### `editor:save()`
+
+```lua
+editor:save() -> nil
+```
+
+Saves the current buffer to its file. If the buffer has no filename, opens a [`file_prompt`](#file_prompt) to ask for one, and updates the filetype and highlighter based on the chosen name. Before writing, strips trailing whitespace from every line. Appends a final newline to the file content if one is not already present (so saved files always end with `\n`). Reports success or failure in the status bar.
+
+---
+
+###### `editor:revert_file()`
+
+```lua
+editor:revert_file() -> nil
+```
+
+Reloads the current buffer from disk, discarding all unsaved changes. If the buffer is modified, prompts for confirmation via `yn_prompt` first. On success, replaces the line table, clears undo/redo stacks, and resets the cursor to a valid position. Reports success or failure.
+
+---
+
+###### `editor:_open_file_as_buffer(filename)`
+
+```lua
+editor:_open_file_as_buffer(filename: string) -> integer
+```
+
+Opens a file as a buffer. If the file is already open in an existing buffer (matched by normalised path), switches to that buffer instead of opening a duplicate. Otherwise, loads the file, creates a new buffer with `make_buffer`, appends it to `editor.buffers`, and switches to it. Returns the index of the buffer in `editor.buffers`.
+
+The leading underscore signals that this is an internal function called by `open_file` and `recursive_search`, not directly by keybinds.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `filename` | `string` | The path to open |
+
+**Returns:** The buffer index.
+
+---
+
+###### `editor:switch_to_buffer(idx)`
+
+```lua
+editor:switch_to_buffer(idx: integer) -> nil
+```
+
+Saves the current editor state into the current buffer's entry, then loads buffer `idx` into the editor. Updates the terminal title and reports the buffer index, count, and filename in the status bar.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `idx` | `integer` | The 1-based index into `editor.buffers` |
+
+---
+
+###### `editor:open_file()`
+
+```lua
+editor:open_file() -> nil
+```
+
+Opens a `file_prompt` and calls `_open_file_as_buffer` with the result. Bound to `C-x C-f`.
+
+---
+
+###### `editor:kill_buffer()`
+
+```lua
+editor:kill_buffer() -> nil
+```
+
+Closes the current buffer. Prompts for confirmation if the buffer is modified. Removes the buffer from `editor.buffers`. If this was the last buffer, creates a new empty buffer in its place. Switches to an adjacent buffer otherwise. Reports the name of the killed buffer.
+
+---
+
+###### `editor:buffer_picker()`
+
+```lua
+editor:buffer_picker() -> nil
+```
+
+Opens a full-screen interactive buffer list. All open buffers are shown with their modification status and filename. Navigate with `↑`/`↓` or `C-p`/`C-n`. Press `Enter` to switch to the selected buffer. Press `k` to kill the selected buffer (removes it from the list without switching). Press `C-g` to cancel and return to the current buffer.
+
+---
+
+###### `editor:next_buffer()`
+
+```lua
+editor:next_buffer() -> nil
+```
+
+Switches to the next buffer in `editor.buffers`, wrapping around from the last to the first. Does nothing (with a message) if only one buffer is open. Bound to `C-]`.
+
+---
+
+###### `editor:prev_buffer()`
+
+```lua
+editor:prev_buffer() -> nil
+```
+
+Switches to the previous buffer, wrapping around from the first to the last. Bound to `C-\`.
+
+---
+
+###### `editor:goto_line_prompt()`
+
+```lua
+editor:goto_line_prompt() -> nil
+```
+
+Opens a `mini_prompt` asking for a line number, then moves the cursor to that line (1-based). Clamps the target line to the buffer extent. Calls `adjust_scroll`. Reports the destination line or an error if the input is not a valid number. Bound to `M-g`.
+
+---
+
+###### `editor:isearch()`
+
+```lua
+editor:isearch() -> nil
+```
+
+Implements incremental search, bound to `C-s`. Enters a sub-loop that reads characters and updates the search results with every keystroke. As the pattern grows, all matches are highlighted in the buffer using `COLOR.SEARCH_MATCH`. The cursor jumps to the nearest match forward from the starting position. `C-s` advances to the next match; `C-r` reverses direction. `Enter` confirms; `C-g` cancels and restores the cursor.
+
+Search is smart-case: lower-case-only patterns search case-insensitively; patterns with any upper-case character are case-sensitive.
+
+On confirmation, the matched text is left as an ephemeral selection.
+
+---
+
+###### `editor:search_replace()`
+
+```lua
+editor:search_replace() -> nil
+```
+
+Implements search and replace, bound to `M-%`. Prompts for a search pattern and a replacement string via `mini_prompt`. Both are treated as plain text (not Lua patterns). Applies the replacement globally across all lines of the buffer in a single pass using `string.gsub` with escaped pattern and replacement strings. Records a single undo checkpoint for the entire operation. Reports the number of replacements made.
+
+---
+
+###### `editor:recursive_search()`
+
+```lua
+editor:recursive_search() -> nil
+```
+
+Implements the recursive grep interface, bound to `C-r` in normal mode. Prompts for a search term, then calls `collect_files` to build the list of all files under `.`, and `search_in_file` on each. Displays results in a full-screen list with syntax highlighting on the matching lines. Navigate with `↑`/`↓` or `C-p`/`C-n`; `Enter` opens the file and jumps to the match; `C-g` cancels.
+
+---
+
+###### `editor:run_command()`
+
+```lua
+editor:run_command() -> nil
+```
+
+Bound to `M-x`. Opens a `mini_prompt` and passes the input to `lua_eval` (the C-side evaluator). The result is displayed in the status bar. This exposes the full Lua runtime to the user at runtime — the global `ed` is the live editor table, so expressions like `ed.cursor_row` or `ed:save()` work as expected.
+
+---
+
+###### `editor:run_shell()`
+
+```lua
+editor:run_shell() -> nil
+```
+
+Bound to `M-!`. Opens a `mini_prompt` for a shell command, runs it with `io.popen` (capturing stderr via `2>&1`), and displays the first line of output in the status bar (truncated to fit if necessary). Reports `"Done"` if the command produces no output.
+
+---
+
+###### `editor:init(filenames)`
+
+```lua
+editor:init(filenames: table) -> nil
+```
+
+Initialises the editor session. Called once at startup. Starts ncurses, queries the screen size, calls `setup_colors`, loads all files named in `filenames` into buffers, sets the active buffer to the first one, and updates the terminal title. If `filenames` is empty, creates one empty buffer.
+
+| Parameter | Type | Description |
+|---|---|---|
+| `filenames` | `table` | A list of file path strings. May be empty. |
+
+---
+
+###### `editor:run()`
+
+```lua
+editor:run() -> nil
+```
+
+The main event loop. Calls `editor:draw()`, reads a key with `wch()`, and dispatches it through the keymaps: first to `ac_handle` if autocomplete is active, then to the Meta keymap (if an Escape was just read), then to the `C-x` keymap (if `C-x` was the previous key), then to the main keymap, and finally — for printable characters — to `insert_char`.
+
+Tracks `prev_was_yank` so that `M-y` (yank-pop) knows whether the previous command was a yank. Runs until `editor._quit` is set to `true`.
+
+---
+
+###### `editor:cleanup()`
+
+```lua
+editor:cleanup() -> nil
+```
+
+Tears down the editor session: saves the current editor state back into its buffer entry, calls `end_ncurses` to restore the terminal, and calls `close_log` to flush and close the log file. Called both on normal exit and in the error handler, so the terminal is always properly restored.
+
+---
+
+### C Reference
+
+The C layer (`main.c`) is a thin bridge between Lua and the system. Every function in it follows the same pattern: extract arguments from the Lua stack, perform a system call, push results back onto the stack, and return the number of results. No editor logic lives here. The C functions are registered as Lua globals by the `bindings` table in `main`, making them available to `main.lua` as ordinary Lua functions.
+
+#### Options
+
+---
+
+##### `bindings[]`
+
+```c
+static const struct { const char *name; lua_CFunction func; } bindings[]
+```
+
+An array of name–function pairs that maps C functions to Lua global names. Each entry is registered at startup by iterating the array and calling `lua_pushcfunction` / `lua_setglobal`. Adding a new C function to Lume requires adding an entry here in addition to writing the function itself.
+
+The array is terminated by a `{NULL, NULL}` sentinel.
+
+---
+
+#### Functions
+
+---
+
+##### `on_sigwinch`
+
+```c
+static void on_sigwinch(int sig)
+```
+
+Signal handler for `SIGWINCH`, the terminal resize signal. Sets the global flag `g_resize = 1`. The flag is checked by `l_resize_terminal` at the start of each draw cycle.
+
+---
+
+##### `push_error`
+
+```c
+static int push_error(lua_State *L, const char *msg)
+```
+
+A convenience function used by C functions that can fail. Pushes `nil` and the error string `msg` onto the Lua stack and returns 2 (the number of return values). Following Lua convention, failure is represented as `nil, error_string`.
+
+---
+
+##### `l_init_ncurses`
+
+**Lua name:** *(called only from `editor:init`)*, not exposed as a named global but registered implicitly.
+
+**Lua signature:** `init_ncurses() -> nil`
+
+```c
+static int l_init_ncurses(lua_State *L)
+```
+
+Initialises the ncurses library. In order: sets the locale (required for UTF-8 terminal input), calls `initscr`, enables `cbreak` and `raw` mode (so keypresses are delivered immediately without buffering or interpretation), disables echo, enables keypad mode (so arrow keys produce single key codes rather than escape sequences), disables the cursor, starts colour mode, enables use of default terminal colours (`use_default_colors`), initialises colour pair 1 (black on white, used for the cursor block), and installs `on_sigwinch` as the `SIGWINCH` handler.
+
+---
+
+##### `l_end_ncurses`
+
+**Lua signature:** `end_ncurses() -> nil`
+
+```c
+static int l_end_ncurses(lua_State *L)
+```
+
+Calls `endwin()` to restore the terminal to its pre-ncurses state. Must be called before the program exits, or the terminal will be left in raw mode.
+
+---
+
+##### `l_resize_terminal`
+
+**Lua signature:** `resize_terminal() -> nil`
+
+```c
+static int l_resize_terminal(lua_State *L)
+```
+
+Checks the `g_resize` flag (set by `on_sigwinch`). If set, clears the flag, then calls `endwin()` followed by `refresh()` and `clearok(stdscr, TRUE)` to force ncurses to re-query the terminal dimensions and redraw from scratch. This is the correct way to handle a resize in ncurses. Called at the top of each `editor:draw` cycle.
+
+---
+
+##### `l_refresh_screen`
+
+**Lua signature:** `refresh_screen() -> nil`
+
+```c
+static int l_refresh_screen(lua_State *L)
+```
+
+Calls `wrefresh(stdscr)` to flush the ncurses virtual screen buffer to the terminal. Called at the end of each draw cycle and after each prompt draw.
+
+---
+
+##### `l_get_wchar`
+
+**Lua signature:** `get_wchar() -> integer`
+
+```c
+static int l_get_wchar(lua_State *L)
+```
+
+Calls `wget_wch(stdscr, &ch)` to read one wide character of input. Returns the character as a Lua integer (a Unicode code point for regular characters, or an ncurses key code for special keys). Returns `-1` on error or if no input is available.
+
+---
+
+##### `l_set_title`
+
+**Lua signature:** `set_title(title: string) -> nil`
+
+```c
+static int l_set_title(lua_State *L)
+```
+
+Sets the terminal window title by writing the OSC 0 escape sequence (`\033]0;title\007`) directly to stdout. This works in most terminal emulators that support xterm title sequences. Has no effect in terminals that do not support them.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `string` | The title string |
+
+---
+
+##### `l_get_screen_size`
+
+**Lua signature:** `get_screen_size() -> integer, integer`
+
+```c
+static int l_get_screen_size(lua_State *L)
+```
+
+Calls `getmaxyx(stdscr, rows, cols)` to query the current terminal dimensions. Returns rows and columns as two integers. Note that the column count returned is `cols + 1` — this compensates for an off-by-one in the ncurses `getmaxyx` macro on some implementations.
+
+**Returns:** `rows, cols`
+
+---
+
+##### `l_clear_screen`
+
+**Lua signature:** `clear_screen() -> nil`
+
+```c
+static int l_clear_screen(lua_State *L)
+```
+
+Calls ncurses `clear()`, which marks the entire virtual screen as blank. The actual terminal is not cleared until the next `refresh_screen()` call.
+
+---
+
+##### `l_move_cursor`
+
+**Lua signature:** `move_cursor(y: integer, x: integer) -> nil`
+
+```c
+static int l_move_cursor(lua_State *L)
+```
+
+Calls ncurses `move(y, x)` to position the ncurses internal cursor. This does not move the editor's logical cursor; it positions the ncurses drawing cursor used by subsequent `print_at` calls.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `integer` | Row (0-based, from top) |
+| 2 | `integer` | Column (0-based, from left) |
+
+---
+
+##### `l_print_at`
+
+**Lua signature:** `print_at(y: integer, x: integer, str: string) -> nil`
+
+```c
+static int l_print_at(lua_State *L)
+```
+
+Calls `mvprintw(y, x, "%s", str)` to print a string at the given screen position. The `%s` format is used rather than passing `str` directly as the format string, which prevents any `%` characters in the string from being interpreted as format specifiers.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `integer` | Row |
+| 2 | `integer` | Column |
+| 3 | `string` | The string to print |
+
+---
+
+##### `l_set_reverse`
+
+**Lua signature:** `set_reverse(on: boolean) -> nil`
+
+```c
+static int l_set_reverse(lua_State *L)
+```
+
+Enables or disables the ncurses `A_REVERSE` attribute (swaps foreground and background colours). Used for the status bar, gutter highlights, and prompt rendering.
+
+---
+
+##### `l_set_bold`
+
+**Lua signature:** `set_bold(on: boolean) -> nil`
+
+```c
+static int l_set_bold(lua_State *L)
+```
+
+Enables or disables the ncurses `A_BOLD` attribute. Available for use in custom highlighters, though none of the built-in highlighters currently use it.
+
+---
+
+##### `l_set_color`
+
+**Lua signature:** `set_color(pair: integer, on: boolean) -> nil`
+
+```c
+static int l_set_color(lua_State *L)
+```
+
+Enables or disables a specific ncurses colour pair. `pair` is an index corresponding to one of the pairs initialised by `l_init_color_pair`. When `on` is `true`, `attron(COLOR_PAIR(pair))` is called; when `false`, `attroff(COLOR_PAIR(pair))`.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `integer` | Colour pair index |
+| 2 | `boolean` | `true` to enable, `false` to disable |
+
+---
+
+##### `l_init_color_pair`
+
+**Lua signature:** `init_color_pair(pair: integer, fg: integer, bg: integer) -> nil`
+
+```c
+static int l_init_color_pair(lua_State *L)
+```
+
+Calls ncurses `init_pair(pair, fg, bg)` to define a colour pair. `fg` and `bg` are standard ncurses colour numbers (0–7 for standard colours, or `-1` for the terminal default). This is called for all pairs by `setup_colors` at startup, and may be called again at runtime to redefine colours.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `integer` | Pair index (1–255) |
+| 2 | `integer` | Foreground colour number, or `-1` for default |
+| 3 | `integer` | Background colour number, or `-1` for default |
+
+---
+
+##### `l_save_file`
+
+**Lua signature:** `save_file(path: string, content: string) -> true | nil, string`
+
+```c
+static int l_save_file(lua_State *L)
+```
+
+Writes `content` to the file at `path`, creating or truncating the file. Returns `true` on success. On failure, returns `nil` and an error string (`"Open failed"` or `"Write failed"`).
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `string` | File path |
+| 2 | `string` | File content |
+
+**Returns:** `true` on success, or `nil, error_string` on failure.
+
+---
+
+##### `l_load_file`
+
+**Lua signature:** `load_file(path: string) -> string | nil, string`
+
+```c
+static int l_load_file(lua_State *L)
+```
+
+Reads the entire content of the file at `path` and returns it as a Lua string. On failure, returns `nil` and an error string. The file is opened in text mode (`"r"`), so line ending translation is platform-dependent.
+
+**Returns:** File content string, or `nil, error_string`.
+
+---
+
+##### `l_list_dir`
+
+**Lua signature:** `list_dir(path: string) -> table | nil`
+
+```c
+static int l_list_dir(lua_State *L)
+```
+
+Opens the directory at `path` and returns a Lua table containing the names of all entries (including `.` and `..`). Returns `nil` if the directory cannot be opened. The order of entries matches the order returned by `readdir`, which is filesystem-dependent and not sorted.
+
+**Returns:** A table of filename strings, or `nil`.
+
+---
+
+##### `l_stat_file`
+
+**Lua signature:** `stat_file(path: string) -> string | nil`
+
+```c
+static int l_stat_file(lua_State *L)
+```
+
+Calls `stat(path, &st)` and returns a string describing the file type: `"file"` for a regular file, `"dir"` for a directory, `"other"` for anything else (symlinks, devices, sockets, etc.). Returns `nil` if `stat` fails (file does not exist, permission denied, etc.).
+
+**Returns:** `"file"`, `"dir"`, `"other"`, or `nil`.
+
+---
+
+##### `l_lua_eval`
+
+**Lua signature:** `lua_eval(code: string) -> string`
+
+```c
+static int l_lua_eval(lua_State *L)
+```
+
+Compiles and executes a Lua string in the global interpreter state (`G_L`, which is the same state that `main.lua` runs in). Returns a string result in all cases:
+
+- If compilation fails, returns the compile error message.
+- If execution fails, returns the runtime error message.
+- If execution succeeds and returns one or more values, returns `tostring` of the first value.
+- If execution succeeds and returns nothing, returns `"ok"`.
+
+This function is the engine behind `editor:run_command` (`M-x`). Because it runs in the global state and the editor is exposed as `_G.ed`, evaluated code has unrestricted access to the entire editor. This is intentional — it provides a live Lua REPL into the running editor.
+
+| Lua Parameter | Type | Description |
+|---|---|---|
+| 1 | `string` | Lua source code |
+
+**Returns:** A result or error string.
+
+---
+
+## Guides
+
+The guides in this section walk through specific modifications to Lume, showing how each part of the system fits together. Each guide implements a concrete example from start to finish. The goal is not just to show what to do, but to explain why, so that you can adapt the approach to whatever you want to build.
+
+All modifications described here are made in `main.lua` only. No changes to `main.c` are needed for any of these guides.
+
+---
+
+### Adding a Syntax Highlighter (Basic)
+
+This guide adds syntax highlighting support for the Python language. By the end, `.py` files and Python shebangs will receive keyword highlighting, string and comment support, and correct comment toggling with `M-;`.
+
+The entry point for all of this is [`register_filetype`](#register_filetype). You call it once, at the top level of `main.lua` (anywhere after the `register_filetype` function itself is defined), and that is all that is needed.
+
+**Step 1: Define the keyword set.**
+
+The keyword set is a Lua table used as a set — keys are the keyword strings, values are `true`. This table is used by the autocomplete system to offer keyword completions.
+
+```lua
+local PYTHON_KW = {
+  ["False"]=true,  ["None"]=true,    ["True"]=true,
+  ["and"]=true,    ["as"]=true,      ["assert"]=true,
+  ["async"]=true,  ["await"]=true,   ["break"]=true,
+  ["class"]=true,  ["continue"]=true,["def"]=true,
+  ["del"]=true,    ["elif"]=true,    ["else"]=true,
+  ["except"]=true, ["finally"]=true, ["for"]=true,
+  ["from"]=true,   ["global"]=true,  ["if"]=true,
+  ["import"]=true, ["in"]=true,      ["is"]=true,
+  ["lambda"]=true, ["nonlocal"]=true,["not"]=true,
+  ["or"]=true,     ["pass"]=true,    ["raise"]=true,
+  ["return"]=true, ["try"]=true,     ["while"]=true,
+  ["with"]=true,   ["yield"]=true,
+}
+```
+
+**Step 2: Write the highlighter function.**
+
+The highlighter takes one line string and returns a list of spans. It does not need to handle multi-line constructs (see [Highlighter](#definitions-highlighter) for why). The pattern here follows the C highlighter: walk the line left to right, identify the next token, push a span for it, advance.
+
+```lua
+local function python_hl(line)
+  local spans, i, n = {}, 1, #line
+  while i <= n do
+    local ch = line:sub(i, i)
+
+    -- Line comment
+    if ch == "#" then
+      push_span(spans, i-1, n-i+1, COLOR.COMMENT)
+      break
+
+    -- String: single or double quoted
+    elseif ch == '"' or ch == "'" then
+      local q, j = ch, i+1
+      -- Handle triple-quote opening — treat the rest of the line as a string.
+      if line:sub(i, i+2) == q:rep(3) then
+        push_span(spans, i-1, n-i+1, COLOR.STRING)
+        break
+      end
+      while j <= n do
+        local c = line:sub(j, j)
+        if c == "\\" then j = j+2
+        elseif c == q then j = j+1; break
+        else j = j+1 end
+      end
+      push_span(spans, i-1, j-i, COLOR.STRING)
+      i = j
+
+    -- Number
+    elseif ch:match("%d") then
+      local j = i
+      while j <= n and line:sub(j,j):match("[%d%.xXa-fA-F_]") do j = j+1 end
+      push_span(spans, i-1, j-i, COLOR.NUMBER)
+      i = j
+
+    -- Identifier or keyword
+    elseif ch:match("[%a_]") then
+      local j = i
+      while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
+      if PYTHON_KW[line:sub(i, j-1)] then
+        push_span(spans, i-1, j-i, COLOR.KEYWORD)
+      end
+      i = j
+
+    else
+      i = i+1
+    end
+  end
+  return spans
+end
+```
+
+**Step 3: Register the filetype.**
+
+```lua
+register_filetype(
+  "python",
+  {"%.py$", "%.pyw$"},
+  {"python3?$", "python$"},
+  PYTHON_KW,
+  "#",
+  python_hl
+)
+```
+
+That is everything. Reload Lume and open a `.py` file — highlighting, comment toggling, and autocomplete keyword suggestions will all work.
+
+---
+
+### Adding a Syntax Highlighter (Advanced)
+
+This guide implements a more sophisticated highlighter for Lua, as a case study in the techniques available within Lume's single-line model. The goal is to show how to handle multiple keyword categories (as the built-in Lua highlighter already does), how to write a more careful string parser, and what the limits of the model are.
+
+Look at the built-in Lua highlighter in `main.lua` as the reference implementation. Compare it to the C highlighter. The C highlighter has one keyword table and one colour for all keywords. The Lua highlighter has three keyword tables (`LUA_DEF`, `LUA_LOGIC`, `LUA_VALUE`) and picks a different colour depending on which table the word is found in. This is the main technique for "advanced" highlighting: sub-categorising tokens and assigning them distinct colours.
+
+**Multiple keyword categories.**
+
+To do this for a new language, define multiple keyword sets:
+
+```lua
+local MY_KW_TYPE    = {["int"]=true, ["void"]=true, ["char"]=true}
+local MY_KW_CONTROL = {["if"]=true,  ["for"]=true,  ["return"]=true}
+local MY_KW_VALUE   = {["true"]=true,["false"]=true, ["null"]=true}
+```
+
+Then in the identifier branch of the highlighter:
+
+```lua
+elseif ch:match("[%a_]") then
+  local j = i
+  while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
+  local word = line:sub(i, j-1)
+  local color = MY_KW_TYPE[word]    and COLOR.KEYWORD_DEF
+             or MY_KW_CONTROL[word] and COLOR.KEYWORD_LOGIC
+             or MY_KW_VALUE[word]   and COLOR.KEYWORD_VALUE
+  if color then push_span(spans, i-1, j-i, color) end
+  i = j
+```
+
+Note the short-circuit evaluation: only one colour is applied per word.
+
+**Adding new colour pairs.**
+
+If the built-in `COLOR` values are not enough, you can define new pairs. Choose a pair number not already in use (see [`COLOR`](#option-color); 16 and above are free), call `init_color_pair` in `setup_colors`, and add a constant to the `COLOR` table:
+
+```lua
+-- In the COLOR table:
+COLOR.MY_CUSTOM = 16
+
+-- In setup_colors():
+init_color_pair(COLOR.MY_CUSTOM, 5, -1)  -- magenta on default
+```
+
+Then use `COLOR.MY_CUSTOM` in your highlighter's `push_span` calls.
+
+**Detecting decorated identifiers.**
+
+Some languages have sigil-prefixed identifiers — Python's decorators (`@name`), shell variables (`$name`), Perl's `$`, `@`, `%`. Handle these by checking the character before entering the identifier branch:
+
+```lua
+elseif ch == "@" and line:sub(i+1, i+1):match("[%a_]") then
+  local j = i+1
+  while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
+  push_span(spans, i-1, j-i+1, COLOR.KEYWORD_DEF)  -- includes the @
+  i = j
+```
+
+**What cannot be done within the single-line model.**
+
+Multi-line strings and block comments cannot be highlighted correctly without carrying state between lines, and Lume does not do this. A `"""` triple-quoted string that starts on line 10 and ends on line 15 cannot be highlighted on lines 11–14 because those lines, processed independently, have no way to know they are inside a string.
+
+The correct thing to do here is nothing: leave those lines unhighlighted. Do not attempt to simulate multi-line state by scanning backward for an unmatched delimiter — this approach produces incorrect results when edits happen in the middle of the file and creates confusing, unpredictable highlighting. An unhighlighted comment is less surprising than a comment that is sometimes highlighted and sometimes not.
+
+---
+
+### Adding a New Editor Function (Basic)
+
+This guide adds a simple function that sorts the lines of the current selection alphabetically. It is a good example of the basic pattern: take the selection, do something to its content, put it back.
+
+The function will be added directly to the `editor` table, invoked via `M-x` for now, and then given a keybind in the next guide.
+
+```lua
+function editor:sort_lines()
+  local s = sel_ordered(self)
+  if not s then
+    self.status_msg = "No selection"
+    return
+  end
+  -- Collect the selected lines
+  local selected = {}
+  for r = s.r1, s.r2 do
+    selected[#selected+1] = self.lines[r+1]
+  end
+  -- Sort them
+  table.sort(selected)
+  -- Write them back, with an undo checkpoint
+  push_undo(self)
+  for i, line in ipairs(selected) do
+    self.lines[s.r1 + i] = line
+  end
+  self.modified   = true
+  self.status_msg = string.format("Sorted %d lines", #selected)
+end
+```
+
+Place this function anywhere in `main.lua` after the `editor` table is defined — near the other `editor:*` functions is conventional.
+
+To call it, open a file, select some lines with `C-Space`, and use `M-x`:
+
+```
+M-x ed:sort_lines()
+```
+
+(Because `editor` is exposed as `_G.ed`, you can call its methods from `M-x` as `ed:method()`.)
+
+The function uses [`sel_ordered`](#sel_ordered) to get the selection, [`push_undo`](#push_undo) to record an undo checkpoint, and sets `status_msg` to report what it did — the three things that almost every editor function does.
+
+---
+
+### Adding a New Editor Function (Advanced)
+
+This guide adds an `editor:align_table()` function that takes a selection of lines containing a common delimiter (such as `=` or `|`) and aligns all occurrences of that delimiter to the same column by padding with spaces. This is the kind of non-trivial transformation that is pleasant to have available but would be cumbersome to do by hand.
+
+```lua
+function editor:align_table()
+  -- Require a selection
+  local s = sel_ordered(self)
+  if not s then self.status_msg = "No selection"; return end
+
+  -- Prompt for the delimiter to align on
+  local delim = mini_prompt(self, "Align on: ")
+  if not delim or delim == "" then self.status_msg = "Cancelled"; return end
+
+  local esc   = escape_pattern(delim)
+  local lines = {}
+
+  -- Collect the selected lines and find the maximum column of the delimiter
+  local max_col = 0
+  for r = s.r1, s.r2 do
+    local line = self.lines[r+1]
+    lines[#lines+1] = line
+    local col = line:find(esc)
+    if col and col-1 > max_col then max_col = col-1 end
+  end
+
+  -- Align: pad each line with spaces before the delimiter so it lands at max_col
+  push_undo(self)
+  for i, line in ipairs(lines) do
+    local col = line:find(esc)
+    if col then
+      local before = line:sub(1, col-1):gsub("%s+$", "")  -- trim trailing spaces
+      local after  = line:sub(col)
+      local pad    = max_col - #before
+      self.lines[s.r1 + i] = before .. string.rep(" ", math.max(0, pad)) .. after
+    end
+  end
+
+  self.modified   = true
+  self.status_msg = string.format("Aligned on '%s'", delim)
+end
+```
+
+This function demonstrates several things worth noting:
+
+- It uses [`mini_prompt`](#mini_prompt) inside an editor method. Prompts can be called from any editor function because they take `ed` (or `self`) as their first argument and use the same screen layout as any other prompt.
+- It uses [`escape_pattern`](#escape_pattern) so that the delimiter can contain characters that are special in Lua patterns (e.g. `|`, `+`, `.`).
+- It trims trailing whitespace from the left side before padding, so repeated applications do not accumulate spaces.
+- A single `push_undo` covers the entire transformation.
+
+---
+
+### Adding a Keybind (Control)
+
+Control-key bindings live in the `main_map` table returned by [`make_keymaps`](#make_keymaps). To add one, either modify `make_keymaps` directly or add to the table after it is returned.
+
+The cleanest approach for a personal modification is to modify `make_keymaps`. Find the `main_map` table and add your entry:
+
+```lua
+-- In make_keymaps, inside the main_map table:
+[KEY.CTRL_T] = function()
+  ed:sort_lines()
+  ed:adjust_scroll()
+end,
+```
+
+`CTRL_T` is the code for Control-T. The key codes for control characters are their ASCII control codes: `C-a = 1`, `C-b = 2`, and so on. `C-t = 20`. You can either add the name to the [`KEY`](#option-key) table (`KEY.CTRL_T = 20`) or use the raw integer.
+
+If you want to add the binding without modifying `make_keymaps`, you can do so after the keymaps are created in `editor:run`:
+
+```lua
+function editor:run()
+  local main_map, meta_map, cx_map = make_keymaps(self)
+  -- Add a custom binding after the fact:
+  main_map[20] = function()  -- CTRL_T = 20
+    self:sort_lines()
+    self:adjust_scroll()
+  end
+  -- ... rest of the run loop unchanged
+end
+```
+
+Be careful not to shadow an existing binding. Check the full `main_map` in `make_keymaps` to confirm the key is not already in use.
+
+---
+
+### Adding a Keybind (Meta)
+
+Meta bindings follow the same pattern, but use `meta_map`. Meta keys are the character codes of the key pressed after Escape. To bind `M-t`:
+
+```lua
+-- In make_keymaps, inside the meta_map table:
+[string.byte("t")] = function()
+  ed:align_table()
+  ed:adjust_scroll()
+end,
+```
+
+`string.byte("t")` returns the ASCII code for `t` (116). You can also write `116` directly, but `string.byte` is more readable.
+
+---
+
+### Adding a Keybind (Control-x)
+
+`C-x` prefix bindings live in `cx_map`. The pattern is identical:
+
+```lua
+-- In make_keymaps, inside the cx_map table:
+[KEY.CTRL_T] = function()
+  ed:sort_lines()
+end,
+```
+
+This would be invoked by pressing `C-x` followed by `C-t`. The `C-x` prefix is a good choice for less frequently used commands that do not need a one-key shortcut.