This document explains the design, algorithms, and engineering implementation of the Text Reflow system in szn.
When a terminal pane is resized (e.g., when the user drags the mouse or splits the screen), standard terminal behavior simply truncates or pads lines with trailing spaces. szn implements a smart Text Reflow system that dynamically wraps and unwraps text to fit the new width while preserving context, spacing, and script integrity.
graph TD
A[Grid Resize Event] --> B[Identify Active Text Range]
B --> C[Flatten Physical Lines into Logical Lines]
C --> D[Rewrap Logical Lines to New Width]
D --> E[Reconstruct Grid Lines & Scrollback History]
To reconstruct the original stream of text (logical lines) from the grid’s raw physical rows, szn tracks soft-wraps on each physical line:
wrapped: bool in GridLine:
true: The row naturally overflowed the screen’s right edge and auto-wrapped to the next row.false: The row ended because of an explicit line break (e.g., \n, carriage return, or the end of a block of text).wrapped = true are flattened back into a single continuous array of cells, representing the original unbroken paragraph.Unlike Latin-based scripts where characters are rendered sequentially side-by-side, Tai scripts (Thai U+0E00–U+0E7F and Lao U+0E80–U+0EFF) use vertically and horizontally combining glyphs to form a single visual cluster (or syllable core).
Splitting a Thai or Lao cluster across line boundaries makes the text unreadable and corrupts the script.
A single Thai or Lao character cell is defined as a base consonant that may contain up to two combining marks (stored inside comb1 and comb2 of the Cell struct). A cluster spans across a sequence of cells matching this syntax:
[Leading Vowel]? ➔ Base Consonant [รร]? ➔ [Following Vowels]* ➔ [Right-Attaching Marks]*
า/າ + ะ/ະ). findThaiClusterEnd consumes all consecutive following vowels into the syllable cluster to prevent illegal wraps such as เกา|ะ or ເກາ|ະ.Display.renderContent’s row pre-pass (src/server/render.zig).The function findThaiClusterEnd identifies these boundary rules to ensure that a cluster is treated as an indivisible unit during wrapping for both Thai and Lao scripts.
Thai orthography does not insert spaces between words. To keep words readable without awkward hyphenation or mid-word splits, szn implements a two-tier line-breaking architecture:
libthaiWhen Thai characters are detected in a logical line, szn consults libthai (dynamically loaded at runtime from standard system paths like /opt/homebrew/lib/ or /usr/lib/ via getLibThai):
thai.findWordBreaks maps the logical line’s UTF-32 codepoints into libthai’s word-breaking engine (th_brk_wc_find_breaks).libthai are translated back to terminal cell indices.src/grid.zig, the algorithm prioritizes breaking at these dictionary-confirmed word boundaries whenever a line overflows new_width.If libthai is not installed on the host system or a token is absent from the dictionary, szn falls back to phonetic syllable boundary detection to prevent orphan consonants:
วไป. Since “ว” cannot start a Thai syllable before a leading vowel like “ไ”, this is visually corrupt.O(1) Backtracking Heuristic:
first_thai_idx (the start of the contiguous Thai word/token), cleanly wrapping the entire word to the next line.O(1) amortized time.ๆ (Mai Yamok) and ฯ (Paiyannoi) must never appear at the beginning of a line. When spaced according to typographic conventions (e.g. ต่าง ๆ), the space scanner rejects breaking before the mark, and fallback logic backtracks to wrap the preceding word along with the mark.สัตว์, แพทย์, ศุกร์, จันทร์) represent the silent coda of a syllable and can never start a line. If a line break would place a Thanthakhat-marked consonant (or its double-consonant cluster like ทร์) at column 0, findThaiSyllableStart backtracks to the syllable’s initial consonant or leading vowel.Instead of separate grow and shrink logic, szn runs a unified, lossless, three-step reflow loop:
process_limit (the last non-empty row containing actual text). Trailing empty rows at the bottom of the screen are ignored to prevent them from scrolling active text into history.wrapped flag.char = 0) are trimmed, while explicit space characters (char = ' ') are preserved. This prevents words from merging or accumulating extra space on repeated resizes.new_width.libthai dictionary word boundaries (findWordBreaks).cellHasMaiHanAkat).findThaiClusterEnd).is_padding matches).wrapped = true, and padded with empty char = 0 cells to the new width.grid.history).In addition to linguistic script clustering, szn prevents breaking numbers across line boundaries in awkward positions:
szn backtracks the line break to the start of the number, wrapping the entire number to the next line.1,234,567.88), keeping the entire number on a single line could leave large empty gaps. However, breaking it at arbitrary points (like right before a decimal point) looks incorrect.szn looks for the last comma (,) that fits on the current line:
1,234,567.88 into 1,234, on the first line and 567.88 on the second).is_padding = true) are wrapped together to prevent halves from splitting onto separate lines.", ', `) are not stranded at the end of a line; the wrap backtracks so the quote travels with the following word. Closing quotes are not left stranded alone at the start of the next line; when a closing quote is the cluster that no longer fits and it is attached to a preceding word, that word moves with the quote (when it fits on the new line).char = 0) from typed spaces (char = ' '), users can drag-shrink and drag-grow the pane repeatedly without any text degradation.To optimize performance and maintain compatibility with interactive fullscreen applications (which expect standard character-by-character VT100-style wrapping limits at the right margin), szn only executes the full text reflow algorithm automatically during window or pane resize events.
To apply smart wrapping rules retrospectively to stream output (e.g., after displaying a text document with cat), users can manually trigger a forced reflow of the current active pane at its current width.
Prefix + r (Ctrl-b + r) triggers a forced reflow of the active pane.reflow-pane (alias reflowp) forces a reflow on the active pane.