docs: v1.1 + v1.2 implementation plans, writing-canvas spec, and execution handoff
a59c14199fdc3e3e5fc29db871a6384d0364107f
Kevin Kortum <kevinkortum@me.com> · 2026-06-28 08:14
parent e4e20ae8
4 files changed
docs/superpowers/2026-06-28-glint-handoff.md +69 −0
@@ -0,0 +1,69 @@
+# glint — Handoff (2026-06-28)
+
+Pick-up doc for a fresh conversation. Everything needed to execute the two pending increments.
+
+## Where things stand
+
+- **Repo:** `~/Developer/Home/glint` — Go 1.26.4, module path `glint`, packages under `internal/`.
+- **v1 is DONE and merged to `main`** (modeless terminal markdown editor: config, styling scanner, editor buffer/ops/view, app routing+save/load+quit-confirm, glamour preview, fuzzy picker + daily note, entrypoint). `go vet/build/test ./...` clean. v1 was built via subagent-driven-development; its final whole-branch review caught and fixed 3 cross-package bugs (open-while-dirty data loss → confirm-then-discard, picker sizing, status-bar layout).
+- **VCS:** the repo is now **jj-colocated** (`.jj` + `.git`). `main` bookmark is at the v1.1 design-spec commit. A git/jj remote **`soft`** → `soft:glint` (soft-serve at `kortum@codex.humdrum.me:23231`) is configured but **nothing has been pushed yet**.
+- **Dependency policy (decided by the user):** use the **newest** versions Go's resolver selects; do **not** pin to specific numbers and do not flag version drift as a defect. (The plan's original exact pins were abandoned because glamour v1.0.0 transitively requires a lipgloss prerelease above v1.1.0 — the two could not both be pinned.)
+
+## Two increments to build, in order
+
+Build **increment 1 fully (merge), then increment 2.** Both modify `editor` rendering; sequencing avoids churn. Increment 2's editor work assumes increment 1's themed editor (`editor` consumes `theme.Theme`, app holds `a.theme`).
+
+### Increment 1 — Themes + Picker + YAML (v1.1)
+- Spec: `docs/superpowers/specs/2026-06-28-glint-theme-picker-design.md`
+- Plan: `docs/superpowers/plans/2026-06-28-glint-theme-picker.md` (7 tasks)
+- Delivers: `internal/theme` package (Flexoki light/dark + charm.land, concrete hexes); macOS light/dark auto-detect; `theme=auto` config key; `Ctrl+T` live theme cycle; glamour preview synced to theme; picker sorts by modified-date with today's daily floated on top; live glamour **preview pane** in the picker; `Ctrl+N` new-note from the query; YAML frontmatter syntax-highlighting. Full-text picker search is explicitly deferred.
+
+### Increment 2 — Writing canvas (v1.2)
+- Spec: `docs/superpowers/specs/2026-06-28-glint-writing-canvas-design.md`
+- Plan: `docs/superpowers/plans/2026-06-28-glint-writing-canvas.md` (3 tasks)
+- Delivers: iA Writer–style canvas — centered, percentage-width text column (`clamp(round(W×0.65),24,100)`) with left/right margins + a top pad; text left-aligned inside it; long paragraphs **soft-wrap** word-aware at the column edge; editor cursor/scroll become **visual-row** aware (Up/Down move by visual line with a goal column; Left/Right & Home/End stay logical); the `Ctrl+R` preview shares the column. Picker keeps its full-width split. Cursor is a themed cell (a TUI can't draw iA's thin bar).
+
+## How to execute
+
+Use the **superpowers:subagent-driven-development** skill (same flow that built v1):
+- Fresh implementer subagent per task; two-stage review (spec compliance + code quality) after each; a broad whole-branch review at the end of each increment.
+- **Models:** the plans contain complete code, so implementers are transcription work → use **haiku**. Reviewers → **sonnet**. Final whole-branch review → **opus**.
+- The plans are TDD with exact code and commands; follow them step-by-step. Don't improvise designs the plans already specify.
+- **Ledger:** progress is tracked in `.superpowers/sdd/progress.md` (git-ignored). It already records v1's tasks and carried-forward Minor findings — read it at start; resume at the first task not marked complete; append a line per completed task. The skill's scripts live at `~/.claude/plugins/cache/claude-plugins-official/superpowers/6.0.3/skills/subagent-driven-development/scripts/` (`task-brief`, `review-package`).
+
+### jj note (important)
+The repo is jj-colocated. The plan steps say `git add` / `git commit` per task — these **work** in a colocated repo (jj auto-imports git operations on the next `jj` command), so you may run them as written. But for VCS *navigation* (status, log, branches, push) prefer **jj** (`jj st`, `jj log`, `jj bookmark`, `jj git push`) and load the **jj-guide** skill before any jj mutation. Recommended shape: do each increment's work on its own jj bookmark (or a git branch), let the per-task `git commit`s land, then at finish use jj to advance `main` and (optionally) `jj git push -b main` to `soft`. After any `git commit`, a quick `jj log` confirms the import.
+
+## Invariants (do not break — reviewers must check)
+
+1. **Explicit foreground:** every styled span, in every theme (light included), gets an explicit theme foreground — never the terminal default. This is the root-cause fix for unreadable text on light terminals.
+2. **Markup-visible:** the editor scanner never adds/removes characters; concatenated span texts equal the raw line; raw markup (`**`, `##`, `[[`, backticks) stays visible. Soft-wrapping (increment 2) is display-only: the buffer is untouched and `Bytes()` round-trips exactly.
+
+## Verify + smoke
+
+Per task and at the end: `go vet ./...`, `go build ./...`, `go test ./...` all clean.
+
+Manual smoke needs a **real terminal** (the editor is an AltScreen TUI; it can't be driven from a non-TTY harness — the agent that built v1 confirmed build/flag-parse/error-path/first-frame render but could not drive keys). Have the user run:
+```bash
+go run . README.md # editor; Ctrl+T themes, Ctrl+R preview, Ctrl+P picker, Ctrl+D daily, Ctrl+N new note
+go run . # bare → picker (mtime order, today on top, preview pane)
+```
+Expected after both increments: readable in a light terminal; Ctrl+T cycles flexoki-light → flexoki-dark → charm; YAML frontmatter shows colored keys/values with muted `---`; picker is newest-first with today's daily on top and a glamour preview pane; text sits in a centered column with margins and long paragraphs soft-wrap.
+
+## Tracking
+
+Update `~/Humdrum/Claude/Projects/glint.md` at checkpoints (delegate doc writes to a Haiku subagent per the user's CLAUDE.md). Capture any new bugs/ideas as Backlog.md tasks in the repo.
+
+## Keybinds (current + planned)
+
+| Key | Action | Status |
+|---|---|---|
+| type / arrows / Enter / Backspace / Del | edit / move | v1 |
+| `Ctrl+S` | save | v1 |
+| `Ctrl+R` | toggle glamour preview | v1 |
+| `Ctrl+P` | fuzzy picker (confirm-then-discard if dirty) | v1 |
+| `Ctrl+D` | today's daily note (confirm-then-discard if dirty) | v1 |
+| `Esc` | back to editor | v1 |
+| `Ctrl+Q` | quit (twice if dirty) | v1 |
+| `Ctrl+T` | cycle theme | v1.1 |
+| `Ctrl+N` | new note from picker query | v1.1 |
docs/superpowers/plans/2026-06-28-glint-theme-picker.md +1713 −0
@@ -0,0 +1,1713 @@
+# glint v1.1 — Theme System + Picker Overhaul Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add light/dark/charm themes (OS auto-detect + `Ctrl+T` live toggle), rework the file picker to sort by modified-date with today's daily floated on top plus a live glamour preview pane and `Ctrl+N` new-note, and syntax-highlight YAML frontmatter.
+
+**Architecture:** Extract theming into a standalone `internal/theme` package consumed by `editor`, `picker`, `app`, and `preview` (no import cycles). The app holds the active `theme.Theme` and pushes it into sub-models; `Ctrl+T` cycles it. The picker gains mtime-aware ranking, a today-float, a split layout with a glamour preview pane, and a new-note path builder. The scanner's frontmatter branch gains per-element coloring while preserving the char-for-char invariant.
+
+**Tech Stack:** Go 1.26, Bubbletea, Bubbles (viewport, textinput), Lipgloss, Glamour, BurntSushi/toml — all already in go.mod at the newest resolver-selected versions.
+
+## Global Constraints
+
+- Module path `glint`; internal packages import as `glint/internal/<pkg>`.
+- **Dependency policy:** use the newest versions Go's resolver selects; do not pin to specific numbers. Do not flag a dependency version as a defect.
+- **Explicit-foreground invariant (now load-bearing for light themes):** every emitted styled span — in every theme — gets an explicit `Foreground`. Never `lipgloss.Style{}` / terminal default.
+- **Markup-visible invariant:** the editor styling scanner never inserts or deletes characters; the concatenation of a line's span texts equals the raw line exactly. This includes the new YAML-frontmatter highlighting.
+- Three themes only: `flexoki-light`, `flexoki-dark`, `charm`. Exact hexes are specified in Task 1 — copy them verbatim.
+- `theme` config values: `auto` (default), `flexoki-light`, `flexoki-dark`, `charm`. `auto` → OS detection; unknown → OS detection (never errors).
+- macOS detection: `defaults read -g AppleInterfaceStyle`; output containing `Dark` → dark, else light. Non-darwin → `flexoki-dark`.
+- Theme cycle order (`Ctrl+T`): `flexoki-light → flexoki-dark → charm → flexoki-light`.
+- New keybinds: `Ctrl+T` cycle theme (global); `Ctrl+N` new note (picker mode). All v1 keybinds and the v1.0 confirm-then-discard behavior unchanged.
+- Out of scope: full-text/ripgrep picker mode; new-note template seeding.
+- TDD per task: write failing test → run (fails) → implement → run (passes) → commit. Each task ends `go vet ./...` clean and the full `go test ./...` green before commit.
+
+---
+
+## File Structure
+
+```
+internal/theme/ NEW package — single source of theme truth
+ theme.go Theme struct, registry, ByName, Next, Resolve, CycleOrder
+ themes.go FlexokiLight(), FlexokiDark(), Charm() — concrete palettes
+ detect.go Detect() + detectFrom() (deterministic parse)
+ theme_test.go all-fields-set per theme; ByName; Resolve; Next/cycle
+ detect_test.go detectFrom parse cases
+internal/editor/
+ theme.go DELETED (moved to internal/theme)
+ scanner.go MOD: take theme.Theme; frontmatter highlighting (Task 3)
+ editor.go MOD: theme field is theme.Theme; New() default FlexokiDark; SetTheme
+ scanner_test.go MOD: use theme.Theme/FlexokiDark; frontmatter corpus (Task 3)
+internal/config/
+ config.go MOD: Theme field (toml `theme`, default "auto"); GlamourStyle default ""
+ config_test.go MOD: theme default + overlay; glamour default ""
+internal/preview/
+ preview.go MOD: add SetStyle(string)
+internal/picker/
+ picker.go MOD: fileEntry+mtime walk, rankEntries, today-float, theme colors,
+ preview pane, Query(), SetTheme/SetStyle, NewNotePath
+ picker_test.go MOD: walkMarkdown returns mtime; rankEntries ordering; NewNotePath
+internal/app/
+ app.go MOD: active theme; Ctrl+T cycle; theme→editor/picker/status/glamour;
+ Ctrl+N new note; pass theme+todayPath+style into picker.New
+ app_test.go MOD: Ctrl+T cycles; Ctrl+N creates+opens; picker still opens/dismisses
+```
+
+---
+
+## Task 1: `internal/theme` package
+
+**Files:**
+- Create: `internal/theme/theme.go`, `internal/theme/themes.go`, `internal/theme/detect.go`
+- Test: `internal/theme/theme_test.go`, `internal/theme/detect_test.go`
+
+**Interfaces:**
+- Consumes: nothing (pure, leaf package; only lipgloss + stdlib).
+- Produces:
+ - `theme.Theme` struct (fields below).
+ - `theme.FlexokiLight() Theme`, `theme.FlexokiDark() Theme`, `theme.Charm() Theme`.
+ - `theme.CycleOrder []string` = `{"flexoki-light","flexoki-dark","charm"}`.
+ - `theme.ByName(name string) (Theme, bool)`.
+ - `theme.Next(name string) Theme` — next theme in CycleOrder, wrapping.
+ - `theme.Resolve(configValue string) Theme`.
+ - `theme.Detect() string`, internal `detectFrom(raw string) string`.
+
+- [ ] **Step 1: Write the failing tests**
+
+Create `internal/theme/theme_test.go`:
+```go
+package theme
+
+import (
+ "testing"
+
+ "github.com/charmbracelet/lipgloss"
+)
+
+func allThemes() []Theme { return []Theme{FlexokiLight(), FlexokiDark(), Charm()} }
+
+func TestEveryThemeHasAllColorsSet(t *testing.T) {
+ for _, th := range allThemes() {
+ colors := map[string]lipgloss.Color{
+ "Text": th.Text, "Heading": th.Heading, "Code": th.Code, "Link": th.Link,
+ "Wikilink": th.Wikilink, "ListMarker": th.ListMarker, "Blockquote": th.Blockquote,
+ "Accent": th.Accent, "Background": th.Background, "Muted": th.Muted,
+ "StatusFg": th.StatusFg, "StatusBg": th.StatusBg, "SelFg": th.SelFg,
+ "SelBg": th.SelBg, "Pointer": th.Pointer,
+ }
+ for name, c := range colors {
+ if c == "" {
+ t.Errorf("theme %q: color %s is empty", th.Name, name)
+ }
+ }
+ if th.Name == "" {
+ t.Error("theme has empty Name")
+ }
+ if th.GlamourStyle == "" {
+ t.Errorf("theme %q has empty GlamourStyle", th.Name)
+ }
+ }
+}
+
+func TestByName(t *testing.T) {
+ for _, name := range CycleOrder {
+ if _, ok := ByName(name); !ok {
+ t.Errorf("ByName(%q) not found", name)
+ }
+ }
+ if _, ok := ByName("nope"); ok {
+ t.Error("ByName(nope) should not be found")
+ }
+}
+
+func TestNextCycles(t *testing.T) {
+ if Next("flexoki-light").Name != "flexoki-dark" {
+ t.Error("light -> dark")
+ }
+ if Next("flexoki-dark").Name != "charm" {
+ t.Error("dark -> charm")
+ }
+ if Next("charm").Name != "flexoki-light" {
+ t.Error("charm -> light (wrap)")
+ }
+ // Unknown name starts the cycle at the first entry's successor is well-defined:
+ if Next("unknown").Name != CycleOrder[0] {
+ t.Errorf("unknown -> %s, want %s", Next("unknown").Name, CycleOrder[0])
+ }
+}
+
+func TestResolve(t *testing.T) {
+ if Resolve("charm").Name != "charm" {
+ t.Error("explicit name should resolve to itself")
+ }
+ // auto and unknown both fall back to OS detection — must be a real registered theme.
+ for _, v := range []string{"auto", "", "bogus"} {
+ got := Resolve(v)
+ if _, ok := ByName(got.Name); !ok {
+ t.Errorf("Resolve(%q) returned unregistered theme %q", v, got.Name)
+ }
+ }
+}
+```
+
+Create `internal/theme/detect_test.go`:
+```go
+package theme
+
+import "testing"
+
+func TestDetectFrom(t *testing.T) {
+ cases := map[string]string{
+ "Dark\n": "flexoki-dark",
+ "Dark": "flexoki-dark",
+ "": "flexoki-light", // macOS light mode leaves the key unset (empty output)
+ "Light": "flexoki-light",
+ }
+ for raw, want := range cases {
+ if got := detectFrom(raw); got != want {
+ t.Errorf("detectFrom(%q) = %q, want %q", raw, got, want)
+ }
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/theme/`
+Expected: FAIL — `undefined: FlexokiLight`, `undefined: Theme`, etc.
+
+- [ ] **Step 3: Implement `theme.go`**
+
+Create `internal/theme/theme.go`:
+```go
+// Package theme is glint's single source of color truth. Every styled span in
+// every theme gets an explicit foreground — no terminal-default fallbacks — so
+// the editor reads cleanly on both light and dark terminals.
+package theme
+
+import "github.com/charmbracelet/lipgloss"
+
+// Theme holds every color glint paints, plus its name and the glamour style the
+// read-preview should use to stay visually in sync.
+type Theme struct {
+ Name string
+ GlamourStyle string
+
+ // Markdown element colors.
+ Text lipgloss.Color
+ Heading lipgloss.Color
+ Code lipgloss.Color
+ Link lipgloss.Color
+ Wikilink lipgloss.Color
+ ListMarker lipgloss.Color
+ Blockquote lipgloss.Color
+ Accent lipgloss.Color
+
+ // UI colors.
+ Background lipgloss.Color
+ Muted lipgloss.Color
+ StatusFg lipgloss.Color
+ StatusBg lipgloss.Color
+ SelFg lipgloss.Color
+ SelBg lipgloss.Color
+ Pointer lipgloss.Color
+}
+
+// CycleOrder is the order Ctrl+T steps through themes.
+var CycleOrder = []string{"flexoki-light", "flexoki-dark", "charm"}
+
+func registry() map[string]Theme {
+ return map[string]Theme{
+ "flexoki-light": FlexokiLight(),
+ "flexoki-dark": FlexokiDark(),
+ "charm": Charm(),
+ }
+}
+
+// ByName looks up a registered theme.
+func ByName(name string) (Theme, bool) {
+ t, ok := registry()[name]
+ return t, ok
+}
+
+// Next returns the theme after name in CycleOrder, wrapping around. An unknown
+// name yields the first theme in the cycle.
+func Next(name string) Theme {
+ idx := 0
+ for i, n := range CycleOrder {
+ if n == name {
+ idx = (i + 1) % len(CycleOrder)
+ break
+ }
+ }
+ t, _ := ByName(CycleOrder[idx])
+ return t
+}
+
+// Resolve picks a theme from a config value: "auto"/"" → OS detection; a known
+// name → that theme; an unknown name → OS detection. It never errors and never
+// returns an empty theme.
+func Resolve(configValue string) Theme {
+ if configValue == "" || configValue == "auto" {
+ t, _ := ByName(Detect())
+ return t
+ }
+ if t, ok := ByName(configValue); ok {
+ return t
+ }
+ t, _ := ByName(Detect())
+ return t
+}
+```
+
+- [ ] **Step 4: Implement `themes.go`**
+
+Create `internal/theme/themes.go`:
+```go
+package theme
+
+import "github.com/charmbracelet/lipgloss"
+
+// FlexokiDark is Steph Ango's Flexoki palette, dark variant. Hexes match the
+// user's `md` navigator and the vault ontology.
+func FlexokiDark() Theme {
+ return Theme{
+ Name: "flexoki-dark",
+ GlamourStyle: "dark",
+ Text: lipgloss.Color("#CECDC3"),
+ Heading: lipgloss.Color("#4385BE"),
+ Code: lipgloss.Color("#879A39"),
+ Link: lipgloss.Color("#3AA99F"),
+ Wikilink: lipgloss.Color("#8B7EC8"),
+ ListMarker: lipgloss.Color("#CE5D97"),
+ Blockquote: lipgloss.Color("#878580"),
+ Accent: lipgloss.Color("#D0A215"),
+ Background: lipgloss.Color("#100F0F"),
+ Muted: lipgloss.Color("#878580"),
+ StatusFg: lipgloss.Color("#100F0F"),
+ StatusBg: lipgloss.Color("#4385BE"),
+ SelFg: lipgloss.Color("#100F0F"),
+ SelBg: lipgloss.Color("#D0A215"),
+ Pointer: lipgloss.Color("#CE5D97"),
+ }
+}
+
+// FlexokiLight is the Flexoki light variant — the fix for unreadable text on
+// cream/light terminals.
+func FlexokiLight() Theme {
+ return Theme{
+ Name: "flexoki-light",
+ GlamourStyle: "light",
+ Text: lipgloss.Color("#100F0F"),
+ Heading: lipgloss.Color("#205EA6"),
+ Code: lipgloss.Color("#66800B"),
+ Link: lipgloss.Color("#24837B"),
+ Wikilink: lipgloss.Color("#5E409D"),
+ ListMarker: lipgloss.Color("#A02F6F"),
+ Blockquote: lipgloss.Color("#6F6E69"),
+ Accent: lipgloss.Color("#AD8301"),
+ Background: lipgloss.Color("#FFFCF0"),
+ Muted: lipgloss.Color("#6F6E69"),
+ StatusFg: lipgloss.Color("#FFFCF0"),
+ StatusBg: lipgloss.Color("#205EA6"),
+ SelFg: lipgloss.Color("#FFFCF0"),
+ SelBg: lipgloss.Color("#AD8301"),
+ Pointer: lipgloss.Color("#A02F6F"),
+ }
+}
+
+// Charm is a charm.land / charmbracelet-brand themed dark palette.
+func Charm() Theme {
+ return Theme{
+ Name: "charm",
+ GlamourStyle: "dark",
+ Text: lipgloss.Color("#FFFDF5"),
+ Heading: lipgloss.Color("#FF5FAF"),
+ Code: lipgloss.Color("#00FFA3"),
+ Link: lipgloss.Color("#5DD5FF"),
+ Wikilink: lipgloss.Color("#B575FF"),
+ ListMarker: lipgloss.Color("#FF5FAF"),
+ Blockquote: lipgloss.Color("#6C6C8A"),
+ Accent: lipgloss.Color("#FFD500"),
+ Background: lipgloss.Color("#16161E"),
+ Muted: lipgloss.Color("#6C6C8A"),
+ StatusFg: lipgloss.Color("#FFFDF5"),
+ StatusBg: lipgloss.Color("#6B50FF"),
+ SelFg: lipgloss.Color("#16161E"),
+ SelBg: lipgloss.Color("#FF5FAF"),
+ Pointer: lipgloss.Color("#00FFA3"),
+ }
+}
+```
+
+- [ ] **Step 5: Implement `detect.go`**
+
+Create `internal/theme/detect.go`:
+```go
+package theme
+
+import (
+ "os/exec"
+ "runtime"
+ "strings"
+)
+
+// Detect returns "flexoki-dark" or "flexoki-light" from the OS appearance. On
+// non-darwin platforms it returns dark. On macOS it reads the global
+// AppleInterfaceStyle key (unset in Light mode → empty output → light).
+func Detect() string {
+ if runtime.GOOS != "darwin" {
+ return "flexoki-dark"
+ }
+ out, _ := exec.Command("defaults", "read", "-g", "AppleInterfaceStyle").Output()
+ return detectFrom(string(out))
+}
+
+// detectFrom parses the raw `defaults read -g AppleInterfaceStyle` output.
+func detectFrom(raw string) string {
+ if strings.Contains(raw, "Dark") {
+ return "flexoki-dark"
+ }
+ return "flexoki-light"
+}
+```
+
+- [ ] **Step 6: Run to verify it passes**
+
+Run: `go test ./internal/theme/`
+Expected: PASS.
+
+- [ ] **Step 7: Vet and commit**
+
+```bash
+go vet ./internal/theme/
+git add internal/theme/
+git commit -m "feat: theme package — flexoki light/dark + charm, detect, resolve"
+```
+
+---
+
+## Task 2: Migrate `editor` to `theme.Theme`
+
+**Files:**
+- Delete: `internal/editor/theme.go`
+- Modify: `internal/editor/scanner.go`, `internal/editor/editor.go`
+- Modify: `internal/editor/scanner_test.go`
+
+**Interfaces:**
+- Consumes: `theme.Theme`, `theme.FlexokiDark` (Task 1).
+- Produces:
+ - `ScanLines(lines []string, th theme.Theme) [][]Span` (param type changed).
+ - `(*Editor).SetTheme(t theme.Theme)`.
+ - `editor.New() *Editor` unchanged signature; default theme is now `theme.FlexokiDark()`.
+
+This is a mechanical type move. The frontmatter still renders all-muted here; Task 3 changes that.
+
+- [ ] **Step 1: Delete the old theme file**
+
+```bash
+git rm internal/editor/theme.go
+```
+
+- [ ] **Step 2: Update `scanner.go` to use `theme.Theme`**
+
+In `internal/editor/scanner.go`, add the import and change every `Theme` to `theme.Theme`. The import block becomes:
+```go
+import (
+ "regexp"
+ "strings"
+
+ "glint/internal/theme"
+
+ "github.com/charmbracelet/lipgloss"
+)
+```
+Change these four signatures (bodies unchanged — they already use `th.Code`, `th.Heading`, etc., which exist on `theme.Theme`):
+```go
+func ScanLines(lines []string, th theme.Theme) [][]Span {
+```
+```go
+func scanLine(row int, line string, st *blockState, th theme.Theme) []Span {
+```
+```go
+func scanInline(text string, th theme.Theme) []Span {
+```
+```go
+func matchToken(r []rune, i int, th theme.Theme) (string, lipgloss.Style, int, bool) {
+```
+
+- [ ] **Step 3: Update `editor.go` to use `theme.Theme` and add `SetTheme`**
+
+In `internal/editor/editor.go`, add the import:
+```go
+import (
+ "strings"
+
+ "glint/internal/theme"
+
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+)
+```
+Change the struct field:
+```go
+ theme theme.Theme
+```
+Change `New` to default to FlexokiDark:
+```go
+func New() *Editor {
+ return &Editor{
+ Lines: []string{""},
+ theme: theme.FlexokiDark(),
+ Width: 80,
+ Height: 24,
+ }
+}
+```
+Add the setter (place it right after `New`):
+```go
+// SetTheme swaps the active theme; the next View re-scans with the new colors.
+func (e *Editor) SetTheme(t theme.Theme) { e.theme = t }
+```
+
+- [ ] **Step 4: Update `scanner_test.go`**
+
+In `internal/editor/scanner_test.go`: add the import `"glint/internal/theme"`, replace every `DefaultDarkTheme()` with `theme.FlexokiDark()`, and **delete** `TestDefaultThemeAllColorsSet` entirely (that invariant now lives in `internal/theme/theme_test.go`). Leave the `lipgloss` import only if still used (it is, by `TestRenderSpansPreservesText` and `TestScanPlainTextGetsExplicitForeground`). The frontmatter test (`TestScanLeadingFrontmatter`) stays as-is — frontmatter is still all-muted in this task.
+
+- [ ] **Step 5: Run editor + whole suite**
+
+Run: `go test ./internal/editor/`
+Expected: PASS (frontmatter still muted; everything else unchanged).
+
+Run: `go test ./...`
+Expected: PASS — `app` and `preview` still compile (they don't reference `editor.Theme`).
+
+- [ ] **Step 6: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/editor/
+git commit -m "refactor: editor consumes theme.Theme; default flexoki-dark; SetTheme"
+```
+
+---
+
+## Task 3: YAML frontmatter highlighting
+
+**Files:**
+- Modify: `internal/editor/scanner.go`
+- Modify: `internal/editor/scanner_test.go`
+
+**Interfaces:**
+- Consumes: `theme.Theme` (Task 2). Uses fields `Accent` (keys), `Text` (values), `ListMarker` (`-` markers), `Muted`/`Blockquote` (delimiters, comments).
+- Produces: no new exported symbols; the frontmatter branch of `scanLine` now emits multiple colored spans instead of one muted span.
+
+Preserve the markup-visible invariant: spans for a line concatenate back to the raw line exactly.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append to `internal/editor/scanner_test.go`:
+```go
+func TestScanFrontmatterHighlightsKeysAndValues(t *testing.T) {
+ th := theme.FlexokiDark()
+ lines := []string{"---", "title: Hello", "tags:", " - one", " - two", "# a comment", "---", "body"}
+ out := ScanLines(lines, th)
+
+ // Char-for-char preservation across every frontmatter line.
+ for i, raw := range lines {
+ if got := spanText(out[i]); got != raw {
+ t.Errorf("line %d: span text %q != raw %q", i, got, raw)
+ }
+ }
+ // Opening and closing --- are muted.
+ if out[0][0].Style.GetForeground() != th.Muted {
+ t.Errorf("opening --- not muted")
+ }
+ if out[6][0].Style.GetForeground() != th.Muted {
+ t.Errorf("closing --- not muted")
+ }
+ // "title:" key portion is Accent; the value is Text.
+ if out[1][0].Style.GetForeground() != th.Accent {
+ t.Errorf("key not Accent-colored, got %v", out[1][0].Style.GetForeground())
+ }
+ if last := out[1][len(out[1])-1]; last.Style.GetForeground() != th.Text {
+ t.Errorf("value not Text-colored, got %v", last.Style.GetForeground())
+ }
+ // List item marker "-" is ListMarker-colored.
+ foundMarker := false
+ for _, sp := range out[3] {
+ if sp.Style.GetForeground() == th.ListMarker {
+ foundMarker = true
+ }
+ }
+ if !foundMarker {
+ t.Errorf("list item dash not ListMarker-colored")
+ }
+ // Comment line is muted.
+ if out[5][0].Style.GetForeground() != th.Muted {
+ t.Errorf("comment not muted")
+ }
+ // After the closing ---, normal text resumes.
+ if out[7][0].Style.GetForeground() != th.Text {
+ t.Errorf("post-frontmatter line should be plain text")
+ }
+}
+```
+Also **replace** the existing `TestScanLeadingFrontmatter` body (its old expectation that `title: x` is muted is now wrong). Replace it with:
+```go
+func TestScanLeadingFrontmatter(t *testing.T) {
+ th := theme.FlexokiDark()
+ lines := []string{"---", "title: x", "---", "body"}
+ out := ScanLines(lines, th)
+ if out[0][0].Style.GetForeground() != th.Muted {
+ t.Errorf("opening --- not muted")
+ }
+ if out[1][0].Style.GetForeground() != th.Accent {
+ t.Errorf("frontmatter key not accent-colored")
+ }
+ if out[3][0].Style.GetForeground() != th.Text {
+ t.Errorf("post-frontmatter line should be plain text")
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/editor/ -run TestScanFrontmatter`
+Expected: FAIL — frontmatter currently renders one muted span, so the key is muted, not Accent.
+
+- [ ] **Step 3: Implement frontmatter highlighting**
+
+In `internal/editor/scanner.go`, replace the frontmatter block inside `scanLine`. The current block is:
+```go
+ // Leading YAML frontmatter: only valid starting at row 0.
+ if st.inFrontmatter {
+ if trimmed == "---" {
+ st.inFrontmatter = false
+ st.frontmatterDone = true
+ }
+ return wholeLine(line, muted)
+ }
+ if row == 0 && trimmed == "---" {
+ st.inFrontmatter = true
+ return wholeLine(line, muted)
+ }
+```
+Replace it with:
+```go
+ // Leading YAML frontmatter: only valid starting at row 0.
+ if st.inFrontmatter {
+ if trimmed == "---" {
+ st.inFrontmatter = false
+ st.frontmatterDone = true
+ return wholeLine(line, muted)
+ }
+ return scanFrontmatter(line, th)
+ }
+ if row == 0 && trimmed == "---" {
+ st.inFrontmatter = true
+ return wholeLine(line, muted)
+ }
+```
+Then add this function near `wholeLine` (after it):
+```go
+// scanFrontmatter highlights one YAML frontmatter line, keeping every character
+// visible: the spans concatenate back to the raw line exactly.
+// - "# comment" -> whole line muted
+// - " - item" -> leading ws + dash (ListMarker) + item (Text)
+// - "key: value" -> "key:" (Accent) + " value" (Text)
+// - anything else -> whole line Text
+func scanFrontmatter(line string, th theme.Theme) []Span {
+ muted := lipgloss.NewStyle().Foreground(th.Blockquote)
+ accent := lipgloss.NewStyle().Foreground(th.Accent)
+ plain := lipgloss.NewStyle().Foreground(th.Text)
+ marker := lipgloss.NewStyle().Foreground(th.ListMarker)
+
+ trimmed := strings.TrimSpace(line)
+
+ // Comment line.
+ if strings.HasPrefix(trimmed, "#") {
+ return wholeLine(line, muted)
+ }
+
+ // List item: optional leading whitespace, then "- ...".
+ if loc := listRe.FindStringIndex(line); loc != nil && strings.HasPrefix(trimmed, "-") {
+ mk := line[:loc[1]] // leading ws + "- "
+ rest := line[loc[1]:] // item text
+ spans := []Span{{Text: mk, Style: marker}}
+ if rest != "" {
+ spans = append(spans, Span{Text: rest, Style: plain})
+ }
+ return spans
+ }
+
+ // key: value — split at the first colon. Keep the colon with the key.
+ if idx := strings.IndexByte(line, ':'); idx >= 0 {
+ key := line[:idx+1] // includes the colon
+ rest := line[idx+1:] // remainder (may start with a space)
+ spans := []Span{{Text: key, Style: accent}}
+ if rest != "" {
+ spans = append(spans, Span{Text: rest, Style: plain})
+ }
+ return spans
+ }
+
+ // Bare line (e.g. a continuation): plain text.
+ return wholeLine(line, plain)
+}
+```
+
+- [ ] **Step 4: Run editor tests**
+
+Run: `go test ./internal/editor/`
+Expected: PASS (new frontmatter test + replaced test + all prior tests).
+
+- [ ] **Step 5: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/editor/scanner.go internal/editor/scanner_test.go
+git commit -m "feat: syntax-highlight YAML frontmatter (keys/values/markers/comments)"
+```
+
+---
+
+## Task 4: Config `theme` key, app active theme, `Ctrl+T` toggle, glamour sync
+
+**Files:**
+- Modify: `internal/config/config.go`, `internal/config/config_test.go`
+- Modify: `internal/preview/preview.go`
+- Modify: `internal/app/app.go`, `internal/app/app_test.go`
+
+**Interfaces:**
+- Consumes: `theme.Resolve`, `theme.Next`, `theme.Theme` (Task 1); `(*editor.Editor).SetTheme` (Task 2).
+- Produces:
+ - `config.Config.Theme string` (toml `theme`, default `"auto"`); `GlamourStyle` default becomes `""`.
+ - `(*preview.Model).SetStyle(s string)`.
+ - App holds `theme theme.Theme`; `Ctrl+T` cycles; status bar uses theme colors; glamour style derived from theme unless `cfg.GlamourStyle` set.
+
+- [ ] **Step 1: Write the failing config test**
+
+In `internal/config/config_test.go`, update `TestDefaultHasSaneValues` to also assert the new defaults — append inside it:
+```go
+ if d.Theme != "auto" {
+ t.Errorf("Theme = %q, want auto", d.Theme)
+ }
+ if d.GlamourStyle != "" {
+ t.Errorf("GlamourStyle default = %q, want empty (theme drives it)", d.GlamourStyle)
+ }
+```
+And add a new test:
+```go
+func TestLoadFromFileOverlaysTheme(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "config.toml")
+ if err := os.WriteFile(path, []byte("theme = \"charm\"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := loadFromFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.Theme != "charm" {
+ t.Errorf("Theme = %q, want charm", cfg.Theme)
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/config/`
+Expected: FAIL — `d.Theme` undefined; default GlamourStyle is `"dark"` not `""`.
+
+- [ ] **Step 3: Update `config.go`**
+
+In `internal/config/config.go`, add the field to the struct:
+```go
+type Config struct {
+ VaultDir string `toml:"vault_dir"`
+ DailySubdir string `toml:"daily_subdir"`
+ DailyFormat string `toml:"daily_format"`
+ GlamourStyle string `toml:"glamour_style"`
+ Theme string `toml:"theme"`
+}
+```
+Change `Default()` — set `Theme: "auto"` and drop the `GlamourStyle` default (leave it `""`):
+```go
+func Default() Config {
+ home, _ := os.UserHomeDir()
+ return Config{
+ VaultDir: filepath.Join(home, "Humdrum"),
+ DailySubdir: "Daily",
+ DailyFormat: "2006-01-02",
+ Theme: "auto",
+ }
+}
+```
+In `loadFromFile`, add a Theme overlay alongside the existing ones (GlamourStyle overlay stays — an explicitly-set non-empty value still overrides):
+```go
+ if fileCfg.Theme != "" {
+ cfg.Theme = fileCfg.Theme
+ }
+```
+
+- [ ] **Step 4: Run config tests**
+
+Run: `go test ./internal/config/`
+Expected: PASS.
+
+- [ ] **Step 5: Add `SetStyle` to preview**
+
+In `internal/preview/preview.go`, add after `SetSize`:
+```go
+// SetStyle changes the glamour style used by the next Render.
+func (m *Model) SetStyle(s string) { m.style = s }
+```
+
+- [ ] **Step 6: Write the failing app test**
+
+Append to `internal/app/app_test.go`:
+```go
+func TestCtrlTCyclesTheme(t *testing.T) {
+ cfg := config.Default()
+ cfg.Theme = "flexoki-light"
+ a := New(cfg)
+ a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
+ if a.theme.Name != "flexoki-light" {
+ t.Fatalf("initial theme = %q, want flexoki-light", a.theme.Name)
+ }
+ a.Update(tea.KeyMsg{Type: tea.KeyCtrlT})
+ if a.theme.Name != "flexoki-dark" {
+ t.Errorf("after one Ctrl+T = %q, want flexoki-dark", a.theme.Name)
+ }
+ a.Update(tea.KeyMsg{Type: tea.KeyCtrlT})
+ if a.theme.Name != "charm" {
+ t.Errorf("after two Ctrl+T = %q, want charm", a.theme.Name)
+ }
+}
+```
+
+- [ ] **Step 7: Run to verify it fails**
+
+Run: `go test ./internal/app/ -run TestCtrlTCyclesTheme`
+Expected: FAIL — `a.theme` undefined.
+
+- [ ] **Step 8: Wire the theme into the app**
+
+In `internal/app/app.go`:
+
+Add the import:
+```go
+ "glint/internal/theme"
+```
+Add a field to `App` (after `cfg`):
+```go
+ theme theme.Theme
+```
+Rewrite `New` to resolve the theme, push it into the editor, and derive the glamour style:
+```go
+func New(cfg config.Config) *App {
+ th := theme.Resolve(cfg.Theme)
+ ed := editor.New()
+ ed.SetTheme(th)
+ a := &App{
+ mode: ModeEditor,
+ cfg: cfg,
+ theme: th,
+ editor: ed,
+ }
+ a.preview = preview.New(a.glamourStyle())
+ return a
+}
+
+// glamourStyle is the explicit config override if set, else the theme's style.
+func (a *App) glamourStyle() string {
+ if a.cfg.GlamourStyle != "" {
+ return a.cfg.GlamourStyle
+ }
+ return a.theme.GlamourStyle
+}
+```
+Add a `Ctrl+T` case to the global key switch (after the `Ctrl+R` case):
+```go
+ case tea.KeyCtrlT:
+ return a.cycleTheme()
+```
+Add the cycle handler (near `togglePreview`):
+```go
+// cycleTheme advances to the next theme and repaints the editor, preview, and
+// (if open) the picker.
+func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
+ a.theme = theme.Next(a.theme.Name)
+ a.editor.SetTheme(a.theme)
+ a.preview.SetStyle(a.glamourStyle())
+ if a.picker != nil {
+ a.picker.SetTheme(a.theme)
+ a.picker.SetStyle(a.glamourStyle())
+ }
+ a.status = "Theme: " + a.theme.Name
+ return a, nil
+}
+```
+Update `statusBar` to use theme colors:
+```go
+func (a *App) statusBar() string {
+ bar := lipgloss.NewStyle().
+ Foreground(a.theme.StatusFg).
+ Background(a.theme.StatusBg).
+ Width(maxInt(a.width, 1))
+ dirty := ""
+ if a.editor.Dirty {
+ dirty = " ●"
+ }
+ left := a.status
+ if left == "" {
+ left = "glint"
+ }
+ return bar.Render(fmt.Sprintf(" %s%s ", left, dirty))
+}
+```
+
+> NOTE: `a.picker.SetTheme` / `a.picker.SetStyle` are added in Task 5. Until then the picker has no `SetTheme`. To keep this task compiling and committable on its own, the `if a.picker != nil` block above will not compile yet. Therefore, in THIS task, write the `cycleTheme` body WITHOUT the picker block:
+> ```go
+> func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
+> a.theme = theme.Next(a.theme.Name)
+> a.editor.SetTheme(a.theme)
+> a.preview.SetStyle(a.glamourStyle())
+> a.status = "Theme: " + a.theme.Name
+> return a, nil
+> }
+> ```
+> Task 5 re-adds the picker repaint lines once `SetTheme`/`SetStyle` exist on the picker.
+
+- [ ] **Step 9: Run app + whole suite**
+
+Run: `go test ./internal/app/ ./internal/config/ ./internal/preview/`
+Expected: PASS.
+
+Run: `go test ./...`
+Expected: PASS.
+
+- [ ] **Step 10: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/config/ internal/preview/ internal/app/
+git commit -m "feat: theme config key, Ctrl+T cycle, themed status bar, glamour sync"
+```
+
+---
+
+## Task 5: Picker — mtime sort, today-float, theme colors
+
+**Files:**
+- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
+- Modify: `internal/app/app.go` (pass theme + today path into `picker.New`; re-add picker repaint in `cycleTheme`)
+
+**Interfaces:**
+- Consumes: `theme.Theme` (Task 1); `config.Config.DailyPath` (existing).
+- Produces:
+ - `picker.fileEntry struct { path string; mod time.Time }` (unexported).
+ - `walkMarkdown(root string) ([]fileEntry, error)` (return type changed).
+ - `rankEntries(all []fileEntry, query, today string) []string` (pure, tested).
+ - `picker.New(root string, th theme.Theme, todayPath string) (*Model, error)` (signature changed).
+ - `(*Model).SetTheme(t theme.Theme)`, `(*Model).Query() string`.
+ - `(*Model).Selected()`, `SetSize`, `Update`, `View` unchanged signatures.
+
+(The preview pane and `SetStyle`/`NewNotePath` arrive in Tasks 6–7. This task delivers ordering + theming with a list-only View.)
+
+- [ ] **Step 1: Write the failing tests**
+
+Replace the body of `TestWalkMarkdownSkipsDotDirsAndNonMarkdown` in `internal/picker/picker_test.go` to account for the new return type — change the result extraction to read `.path`:
+```go
+func TestWalkMarkdownSkipsDotDirsAndNonMarkdown(t *testing.T) {
+ root := t.TempDir()
+ os.WriteFile(filepath.Join(root, "a.md"), nil, 0o644)
+ os.WriteFile(filepath.Join(root, "b.txt"), nil, 0o644)
+ os.MkdirAll(filepath.Join(root, ".git"), 0o755)
+ os.WriteFile(filepath.Join(root, ".git", "c.md"), nil, 0o644)
+ os.MkdirAll(filepath.Join(root, "sub"), 0o755)
+ os.WriteFile(filepath.Join(root, "sub", "d.md"), nil, 0o644)
+
+ entries, err := walkMarkdown(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, e := range entries {
+ got = append(got, e.path)
+ }
+ sort.Strings(got)
+ want := []string{
+ filepath.Join(root, "a.md"),
+ filepath.Join(root, "sub", "d.md"),
+ }
+ if len(got) != len(want) {
+ t.Fatalf("walkMarkdown = %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
+ }
+ }
+}
+```
+Add ranking tests (pure, no filesystem):
+```go
+func TestRankEntriesMtimeDescending(t *testing.T) {
+ base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ all := []fileEntry{
+ {path: "/v/old.md", mod: base},
+ {path: "/v/new.md", mod: base.Add(48 * time.Hour)},
+ {path: "/v/mid.md", mod: base.Add(24 * time.Hour)},
+ }
+ got := rankEntries(all, "", "")
+ want := []string{"/v/new.md", "/v/mid.md", "/v/old.md"}
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
+ }
+ }
+}
+
+func TestRankEntriesTodayFloatsToTop(t *testing.T) {
+ base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ all := []fileEntry{
+ {path: "/v/new.md", mod: base.Add(48 * time.Hour)},
+ {path: "/v/Daily/2026-06-28.md", mod: base}, // oldest, but today
+ }
+ got := rankEntries(all, "", "/v/Daily/2026-06-28.md")
+ if got[0] != "/v/Daily/2026-06-28.md" {
+ t.Errorf("today's note should float to top, got %q", got[0])
+ }
+}
+
+func TestRankEntriesQueryFiltersAndTieBreaksByMtime(t *testing.T) {
+ base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ all := []fileEntry{
+ {path: "/v/alpha.md", mod: base},
+ {path: "/v/alpha-new.md", mod: base.Add(24 * time.Hour)},
+ {path: "/v/zzz.md", mod: base.Add(72 * time.Hour)},
+ }
+ got := rankEntries(all, "alpha", "")
+ // zzz filtered out; both "alpha" files present, newer first on equal score is
+ // not guaranteed (scores differ), but zzz must be absent.
+ for _, p := range got {
+ if p == "/v/zzz.md" {
+ t.Error("zzz.md should not match query 'alpha'")
+ }
+ }
+ if len(got) != 2 {
+ t.Fatalf("got %d matches, want 2", len(got))
+ }
+}
+```
+Add `"time"` to the test file's imports.
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/picker/`
+Expected: FAIL — `fileEntry` undefined, `rankEntries` undefined, `walkMarkdown` returns `[]string`.
+
+- [ ] **Step 3: Rewrite `picker.go` (ordering + theming, list-only View)**
+
+Replace the entire contents of `internal/picker/picker.go` with:
+```go
+// Package picker is a fuzzy file browser over a directory of markdown files.
+// It sorts by modified-date (newest first), floats today's daily note to the
+// top, and paints with the active theme.
+package picker
+
+import (
+ "io/fs"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "glint/internal/theme"
+
+ "github.com/charmbracelet/bubbles/textinput"
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+)
+
+// fileEntry is a markdown file plus its modification time.
+type fileEntry struct {
+ path string
+ mod time.Time
+}
+
+// Model holds the query input, the file set, and the current match list.
+type Model struct {
+ input textinput.Model
+ all []fileEntry
+ root string
+ todayPath string
+ matches []string
+ sel int
+ width int
+ height int
+ theme theme.Theme
+}
+
+// New walks root for markdown files and returns a ready picker themed by th.
+// todayPath is the absolute path of today's daily note (floated to the top when
+// present); pass "" if there is none.
+func New(root string, th theme.Theme, todayPath string) (*Model, error) {
+ files, err := walkMarkdown(root)
+ if err != nil {
+ return nil, err
+ }
+ ti := textinput.New()
+ ti.Prompt = "note › "
+ ti.Placeholder = "filter…"
+ ti.Focus()
+ m := &Model{
+ input: ti,
+ all: files,
+ root: root,
+ todayPath: todayPath,
+ width: 80,
+ height: 24,
+ theme: th,
+ }
+ m.recompute()
+ return m, nil
+}
+
+// SetSize records dimensions.
+func (m *Model) SetSize(w, h int) {
+ m.width = w
+ m.height = h
+}
+
+// SetTheme repaints the picker with a new theme.
+func (m *Model) SetTheme(t theme.Theme) { m.theme = t }
+
+// Query returns the current filter text (used by the app's new-note shortcut).
+func (m *Model) Query() string { return m.input.Value() }
+
+// Update handles query edits and selection movement.
+func (m *Model) Update(msg tea.Msg) tea.Cmd {
+ if key, ok := msg.(tea.KeyMsg); ok {
+ switch key.Type {
+ case tea.KeyUp:
+ if m.sel > 0 {
+ m.sel--
+ }
+ return nil
+ case tea.KeyDown:
+ if m.sel < len(m.matches)-1 {
+ m.sel++
+ }
+ return nil
+ }
+ }
+ var cmd tea.Cmd
+ m.input, cmd = m.input.Update(msg)
+ m.recompute()
+ return cmd
+}
+
+// recompute refilters and reranks against the current query.
+func (m *Model) recompute() {
+ m.matches = rankEntries(m.all, m.input.Value(), m.todayPath)
+ if m.sel >= len(m.matches) {
+ m.sel = 0
+ }
+}
+
+// rankEntries filters all entries by the fuzzy query and orders the survivors.
+// Empty query: today's note first, then modified-date descending. Non-empty:
+// fuzzy score descending, then modified-date descending.
+func rankEntries(all []fileEntry, query, today string) []string {
+ type scored struct {
+ e fileEntry
+ score int
+ }
+ var hits []scored
+ for _, e := range all {
+ label := filepath.Base(e.path)
+ if s, ok := fuzzyMatch(query, label); ok {
+ hits = append(hits, scored{e, s})
+ }
+ }
+ sort.SliceStable(hits, func(i, j int) bool {
+ if query == "" {
+ ti := hits[i].e.path == today
+ tj := hits[j].e.path == today
+ if ti != tj {
+ return ti // today's note floats up
+ }
+ return hits[i].e.mod.After(hits[j].e.mod)
+ }
+ if hits[i].score != hits[j].score {
+ return hits[i].score > hits[j].score
+ }
+ return hits[i].e.mod.After(hits[j].e.mod)
+ })
+ out := make([]string, 0, len(hits))
+ for _, h := range hits {
+ out = append(out, h.e.path)
+ }
+ return out
+}
+
+// label is the vault-relative path shown to the user.
+func (m *Model) label(p string) string {
+ if rel, err := filepath.Rel(m.root, p); err == nil {
+ return rel
+ }
+ return p
+}
+
+// Selected returns the highlighted match's absolute path, or "".
+func (m *Model) Selected() string {
+ if m.sel < 0 || m.sel >= len(m.matches) {
+ return ""
+ }
+ return m.matches[m.sel]
+}
+
+// View renders the query line and the match list, themed.
+func (m *Model) View() string {
+ var b strings.Builder
+ b.WriteString(m.input.View())
+ b.WriteByte('\n')
+ selStyle := lipgloss.NewStyle().Foreground(m.theme.SelFg).Background(m.theme.SelBg)
+ plain := lipgloss.NewStyle().Foreground(m.theme.Text)
+ pointer := lipgloss.NewStyle().Foreground(m.theme.Pointer)
+ rows := m.height - 2
+ if rows < 1 {
+ rows = 1
+ }
+ for i := 0; i < len(m.matches) && i < rows; i++ {
+ label := m.label(m.matches[i])
+ if i == m.sel {
+ b.WriteString(pointer.Render("▸ "))
+ b.WriteString(selStyle.Render(label))
+ } else {
+ b.WriteString(plain.Render(" " + label))
+ }
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+
+// walkMarkdown returns .md files (with mtimes) under root, skipping dot-dirs.
+func walkMarkdown(root string) ([]fileEntry, error) {
+ var out []fileEntry
+ err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return nil // skip unreadable entries
+ }
+ if d.IsDir() {
+ if path != root && strings.HasPrefix(d.Name(), ".") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if strings.EqualFold(filepath.Ext(d.Name()), ".md") {
+ abs, aerr := filepath.Abs(path)
+ if aerr != nil {
+ return nil
+ }
+ var mod time.Time
+ if info, ierr := d.Info(); ierr == nil {
+ mod = info.ModTime()
+ }
+ out = append(out, fileEntry{path: abs, mod: mod})
+ }
+ return nil
+ })
+ return out, err
+}
+
+// fuzzyMatch reports whether query is a case-insensitive subsequence of
+// candidate, scoring contiguous matches higher (fewer gaps -> higher score).
+func fuzzyMatch(query, candidate string) (int, bool) {
+ if query == "" {
+ return 0, true
+ }
+ q := []rune(strings.ToLower(query))
+ c := []rune(strings.ToLower(candidate))
+ score, qi, last := 0, 0, -1
+ for ci := 0; ci < len(c) && qi < len(q); ci++ {
+ if c[ci] == q[qi] {
+ if last >= 0 {
+ score -= ci - last - 1 // penalize gaps
+ }
+ last = ci
+ qi++
+ }
+ }
+ if qi != len(q) {
+ return 0, false
+ }
+ return score, true
+}
+```
+
+> NOTE: `rankEntries` matches against `filepath.Base(e.path)` (the filename) for stable, root-independent tests; the displayed `label` remains the vault-relative path. This matches v1 behavior closely enough (filenames are the dominant signal) and keeps `rankEntries` pure.
+
+- [ ] **Step 4: Update `app.go` to pass theme + today path, and repaint picker on cycle**
+
+In `internal/app/app.go`, change `openPicker` to pass the theme and today's daily path:
+```go
+func (a *App) openPicker() (tea.Model, tea.Cmd) {
+ p, err := picker.New(a.cfg.VaultDir, a.theme, a.cfg.DailyPath(time.Now()))
+ if err != nil {
+ a.status = "Picker failed: " + err.Error()
+ return a, nil
+ }
+ p.SetSize(a.width, a.height-1)
+ a.picker = p
+ a.mode = ModePicker
+ return a, nil
+}
+```
+And re-add the picker repaint to `cycleTheme` (now that `SetTheme` exists; `SetStyle` is added in Task 6 — until then only `SetTheme`):
+```go
+func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
+ a.theme = theme.Next(a.theme.Name)
+ a.editor.SetTheme(a.theme)
+ a.preview.SetStyle(a.glamourStyle())
+ if a.picker != nil {
+ a.picker.SetTheme(a.theme)
+ }
+ a.status = "Theme: " + a.theme.Name
+ return a, nil
+}
+```
+
+- [ ] **Step 5: Run picker + app + whole suite**
+
+Run: `go test ./internal/picker/ ./internal/app/`
+Expected: PASS.
+
+Run: `go test ./...`
+Expected: PASS.
+
+- [ ] **Step 6: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/picker/ internal/app/
+git commit -m "feat: picker sorts by mtime, floats today's daily, themed list"
+```
+
+---
+
+## Task 6: Picker glamour preview pane
+
+**Files:**
+- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
+- Modify: `internal/app/app.go` (pass glamour style into `picker.New`; add `SetStyle` to cycle)
+
+**Interfaces:**
+- Consumes: `preview.New`, `(*preview.Model).SetSize/SetStyle/Render/View` (Tasks 4 + existing).
+- Produces:
+ - `picker.New(root string, th theme.Theme, todayPath, glamourStyle string) (*Model, error)` (signature gains `glamourStyle`).
+ - `(*Model).SetStyle(s string)`.
+ - Split View: list left, rounded-bordered glamour preview right.
+
+- [ ] **Step 1: Write the failing test**
+
+Append to `internal/picker/picker_test.go`:
+```go
+func TestPickerPreviewRendersSelectedFile(t *testing.T) {
+ root := t.TempDir()
+ p := filepath.Join(root, "note.md")
+ os.WriteFile(p, []byte("# Heading\n\nbody text"), 0o644)
+
+ m, err := New(root, theme.FlexokiDark(), "", "dark")
+ if err != nil {
+ t.Fatal(err)
+ }
+ m.SetSize(120, 30)
+ m.recompute() // selects note.md
+ view := m.View()
+ if !strings.Contains(view, "Heading") {
+ t.Errorf("preview pane should render the selected file's heading; view:\n%s", view)
+ }
+}
+```
+Add `"glint/internal/theme"` to the test imports if not already present.
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/picker/ -run TestPickerPreview`
+Expected: FAIL — `New` takes 3 args, not 4; no preview rendering.
+
+- [ ] **Step 3: Add the preview pane to `picker.go`**
+
+In `internal/picker/picker.go`, add the import:
+```go
+ "glint/internal/preview"
+```
+Add fields to `Model` (after `theme`):
+```go
+ preview *preview.Model
+ style string
+```
+Change `New` to accept `glamourStyle` and build a preview model:
+```go
+func New(root string, th theme.Theme, todayPath, glamourStyle string) (*Model, error) {
+ files, err := walkMarkdown(root)
+ if err != nil {
+ return nil, err
+ }
+ ti := textinput.New()
+ ti.Prompt = "note › "
+ ti.Placeholder = "filter…"
+ ti.Focus()
+ m := &Model{
+ input: ti,
+ all: files,
+ root: root,
+ todayPath: todayPath,
+ width: 80,
+ height: 24,
+ theme: th,
+ preview: preview.New(glamourStyle),
+ style: glamourStyle,
+ }
+ m.recompute()
+ return m, nil
+}
+```
+Add `SetStyle` and update `SetSize`/`SetTheme`/`recompute` to size and refresh the preview. Replace `SetSize`, add `SetStyle`, and update `recompute` to call `renderPreview`:
+```go
+// SetSize records dimensions and sizes the preview pane.
+func (m *Model) SetSize(w, h int) {
+ m.width = w
+ m.height = h
+ m.preview.SetSize(m.previewWidth(), h-2)
+}
+
+// SetStyle changes the preview's glamour style.
+func (m *Model) SetStyle(s string) {
+ m.style = s
+ m.preview.SetStyle(s)
+ m.renderPreview()
+}
+
+// previewWidth is the column width of the preview pane (~60%), or 0 when the
+// terminal is too narrow to split.
+func (m *Model) previewWidth() int {
+ if m.width < 60 {
+ return 0
+ }
+ return m.width*6/10 - 2 // minus border
+}
+
+// renderPreview loads the highlighted file into the preview viewport.
+func (m *Model) renderPreview() {
+ if m.previewWidth() <= 0 {
+ return
+ }
+ sel := m.Selected()
+ if sel == "" {
+ _ = m.preview.Render("")
+ return
+ }
+ data, err := os.ReadFile(sel)
+ if err != nil {
+ _ = m.preview.Render("_could not read file_")
+ return
+ }
+ _ = m.preview.Render(string(data))
+}
+```
+Update `recompute` to refresh the preview after ranking:
+```go
+func (m *Model) recompute() {
+ m.matches = rankEntries(m.all, m.input.Value(), m.todayPath)
+ if m.sel >= len(m.matches) {
+ m.sel = 0
+ }
+ m.renderPreview()
+}
+```
+Update `Update` so moving the selection refreshes the preview — in the `KeyUp`/`KeyDown` cases call `m.renderPreview()` before returning:
+```go
+ case tea.KeyUp:
+ if m.sel > 0 {
+ m.sel--
+ m.renderPreview()
+ }
+ return nil
+ case tea.KeyDown:
+ if m.sel < len(m.matches)-1 {
+ m.sel++
+ m.renderPreview()
+ }
+ return nil
+```
+Add `"os"` to the imports. Then rewrite `View` to split list + preview:
+```go
+// View renders the query + themed match list on the left and a glamour preview
+// of the highlighted file on the right (when the terminal is wide enough).
+func (m *Model) View() string {
+ left := m.listView()
+ if m.previewWidth() <= 0 {
+ return left
+ }
+ border := lipgloss.NewStyle().
+ Border(lipgloss.RoundedBorder()).
+ BorderForeground(m.theme.Muted).
+ Width(m.previewWidth()).
+ Height(m.height - 2)
+ right := border.Render(m.preview.View())
+ listCol := lipgloss.NewStyle().Width(m.width - m.previewWidth() - 3).Render(left)
+ return lipgloss.JoinHorizontal(lipgloss.Top, listCol, right)
+}
+
+// listView is the query line plus the themed match list.
+func (m *Model) listView() string {
+ var b strings.Builder
+ b.WriteString(m.input.View())
+ b.WriteByte('\n')
+ selStyle := lipgloss.NewStyle().Foreground(m.theme.SelFg).Background(m.theme.SelBg)
+ plain := lipgloss.NewStyle().Foreground(m.theme.Text)
+ pointer := lipgloss.NewStyle().Foreground(m.theme.Pointer)
+ rows := m.height - 2
+ if rows < 1 {
+ rows = 1
+ }
+ for i := 0; i < len(m.matches) && i < rows; i++ {
+ label := m.label(m.matches[i])
+ if i == m.sel {
+ b.WriteString(pointer.Render("▸ "))
+ b.WriteString(selStyle.Render(label))
+ } else {
+ b.WriteString(plain.Render(" " + label))
+ }
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+```
+(Delete the old `View` that this replaces.)
+
+- [ ] **Step 4: Update `app.go` to pass the glamour style and repaint preview on cycle**
+
+In `openPicker`, pass the glamour style:
+```go
+ p, err := picker.New(a.cfg.VaultDir, a.theme, a.cfg.DailyPath(time.Now()), a.glamourStyle())
+```
+In `cycleTheme`, add the picker `SetStyle` call:
+```go
+ if a.picker != nil {
+ a.picker.SetTheme(a.theme)
+ a.picker.SetStyle(a.glamourStyle())
+ }
+```
+
+- [ ] **Step 5: Run picker + app + whole suite**
+
+Run: `go test ./internal/picker/ ./internal/app/`
+Expected: PASS.
+
+Run: `go test ./...`
+Expected: PASS.
+
+- [ ] **Step 6: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/picker/ internal/app/
+git commit -m "feat: live glamour preview pane in the picker"
+```
+
+---
+
+## Task 7: Picker `Ctrl+N` new note
+
+**Files:**
+- Modify: `internal/picker/picker.go`, `internal/picker/picker_test.go`
+- Modify: `internal/app/app.go`, `internal/app/app_test.go`
+
+**Interfaces:**
+- Consumes: `(*picker.Model).Query` (Task 5).
+- Produces:
+ - `picker.NewNotePath(root, query string) string` (pure, exported, tested).
+ - App: `Ctrl+N` in `ModePicker` creates the note and opens it.
+
+- [ ] **Step 1: Write the failing picker test**
+
+Append to `internal/picker/picker_test.go`:
+```go
+func TestNewNotePath(t *testing.T) {
+ root := "/v"
+ cases := map[string]string{
+ "foo": filepath.Join("/v", "foo.md"),
+ "Folder/Bar": filepath.Join("/v", "Folder", "Bar.md"),
+ "x.md": filepath.Join("/v", "x.md"),
+ " spaced ": filepath.Join("/v", "spaced.md"),
+ }
+ for q, want := range cases {
+ if got := NewNotePath(root, q); got != want {
+ t.Errorf("NewNotePath(%q) = %q, want %q", q, got, want)
+ }
+ }
+ if NewNotePath(root, " ") != "" {
+ t.Error("blank query should yield empty path")
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/picker/ -run TestNewNotePath`
+Expected: FAIL — `undefined: NewNotePath`.
+
+- [ ] **Step 3: Implement `NewNotePath`**
+
+Add to `internal/picker/picker.go` (near the bottom):
+```go
+// NewNotePath builds an absolute note path from a query under root. It trims
+// surrounding whitespace, appends ".md" when absent, and supports "Folder/Name".
+// A blank query yields "".
+func NewNotePath(root, query string) string {
+ rel := strings.TrimSpace(query)
+ if rel == "" {
+ return ""
+ }
+ if !strings.EqualFold(filepath.Ext(rel), ".md") {
+ rel += ".md"
+ }
+ return filepath.Join(root, rel)
+}
+```
+
+- [ ] **Step 4: Run picker tests**
+
+Run: `go test ./internal/picker/`
+Expected: PASS.
+
+- [ ] **Step 5: Write the failing app test**
+
+Append to `internal/app/app_test.go`:
+```go
+func TestCtrlNCreatesNoteFromQuery(t *testing.T) {
+ dir := t.TempDir()
+ cfg := config.Default()
+ cfg.VaultDir = dir
+ a := New(cfg)
+ a.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
+ a.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) // open picker
+ if a.mode != ModePicker {
+ t.Fatalf("expected picker mode")
+ }
+ // Type a name into the picker query.
+ a.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("ideas")})
+ a.Update(tea.KeyMsg{Type: tea.KeyCtrlN})
+
+ if a.mode != ModeEditor {
+ t.Errorf("Ctrl+N should open the new note in the editor, mode = %d", a.mode)
+ }
+ want := filepath.Join(dir, "ideas.md")
+ if a.path != want {
+ t.Errorf("a.path = %q, want %q", a.path, want)
+ }
+ if _, err := os.Stat(want); err != nil {
+ t.Errorf("new note should exist on disk: %v", err)
+ }
+}
+```
+
+- [ ] **Step 6: Run to verify it fails**
+
+Run: `go test ./internal/app/ -run TestCtrlNCreatesNoteFromQuery`
+Expected: FAIL — `Ctrl+N` is unhandled; no file created.
+
+- [ ] **Step 7: Wire `Ctrl+N` in the app's picker routing**
+
+In `internal/app/app.go`, change the `ModePicker` branch of the mode switch to handle `Ctrl+N`:
+```go
+ case ModePicker:
+ switch msg.Type {
+ case tea.KeyEnter:
+ if sel := a.picker.Selected(); sel != "" {
+ if err := a.Load(sel); err != nil {
+ a.status = "Open failed: " + err.Error()
+ }
+ }
+ return a, nil
+ case tea.KeyCtrlN:
+ return a.newNote()
+ }
+ return a, a.picker.Update(msg)
+```
+Add the `newNote` helper (near `openDaily`):
+```go
+// newNote creates a note named after the picker query and opens it.
+func (a *App) newNote() (tea.Model, tea.Cmd) {
+ p := picker.NewNotePath(a.cfg.VaultDir, a.picker.Query())
+ if p == "" {
+ a.status = "Type a name first"
+ return a, nil
+ }
+ if _, err := os.Stat(p); os.IsNotExist(err) {
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ a.status = "New note dir failed: " + err.Error()
+ return a, nil
+ }
+ if err := os.WriteFile(p, []byte{}, 0o644); err != nil {
+ a.status = "New note failed: " + err.Error()
+ return a, nil
+ }
+ }
+ if err := a.Load(p); err != nil {
+ a.status = "Open failed: " + err.Error()
+ }
+ return a, nil
+}
+```
+
+- [ ] **Step 8: Run app + whole suite, vet, build**
+
+Run: `go test ./...`
+Expected: PASS.
+
+Run: `go vet ./... && go build ./...`
+Expected: clean, builds.
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add internal/picker/ internal/app/
+git commit -m "feat: Ctrl+N creates a note from the picker query"
+```
+
+- [ ] **Step 10: Manual smoke (user-driven, real terminal)**
+
+```bash
+go run . README.md # editor — themed; toggle Ctrl+T (light/dark/charm)
+go run . # picker — mtime order, today on top, preview pane, Ctrl+N
+```
+Expected: readable text in a light terminal under flexoki-light; `Ctrl+T` cycles light → dark → charm; YAML frontmatter shows colored keys/values with `---` muted; picker lists newest-first with today's daily on top, a glamour preview pane on the right, and `Ctrl+N` creates a note from the typed name.
+
+---
+
+## Self-Review Notes
+
+**Spec coverage:**
+- A.1 theme package extraction → Task 1 (+ Task 2 migrates editor off `editor.Theme`).
+- A.2 Theme struct (markdown + UI fields, Name, GlamourStyle) → Task 1.
+- A.3 three palettes with concrete hexes → Task 1 `themes.go`.
+- A.4 ByName/Detect/Resolve, macOS detection + non-darwin fallback → Task 1.
+- A.5 config `theme` key default auto; `glamour_style` default "" overrides theme → Task 4.
+- A.6 `Ctrl+T` cycle; editor/status/picker/glamour repaint → Tasks 4 (editor/status/glamour) + 5/6 (picker).
+- B.1 mtime sort + today-float + fuzzy+mtime tiebreak → Task 5 (`rankEntries`).
+- B.2 split preview pane (glamour, theme style, rounded border, updates on move) → Task 6.
+- B.3 `Ctrl+N` new note from query (Folder/Name, .md append, mkdir, open-if-exists) → Task 7.
+- B.4 full-text mode out → not implemented (intentional).
+- C structure/tests → each task is TDD; detection parse is deterministic (`detectFrom`); per-theme all-colors test in Task 1.
+- D YAML frontmatter highlighting (keys/values/markers/comments, char-for-char) → Task 3.
+
+**Type consistency:** `theme.Theme` field names (`Text, Heading, Code, Link, Wikilink, ListMarker, Blockquote, Accent, Background, Muted, StatusFg, StatusBg, SelFg, SelBg, Pointer, Name, GlamourStyle`) are used identically in editor (Tasks 2–3), app (Task 4), and picker (Tasks 5–6). `picker.New` signature grows once in Task 5 (`+th, +todayPath`) and once in Task 6 (`+glamourStyle`); `openPicker` is updated in the same tasks. `cycleTheme` is introduced in Task 4 without the picker block, then the picker repaint lines are added in Tasks 5 (`SetTheme`) and 6 (`SetStyle`) — each task leaves the tree compiling.
+
+**Known follow-ups (not v1.1 blockers):** `rankEntries` matches on filename (`filepath.Base`) rather than the vault-relative label; preview re-renders the file on every selection move (no caching); charm hexes target the brand aesthetic and can be tuned.
docs/superpowers/plans/2026-06-28-glint-writing-canvas.md +838 −0
@@ -0,0 +1,838 @@
+# glint v1.2 — Writing Canvas Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Give the editor an iA Writer–style writing canvas: a centered, percentage-width text column with left/right margins and a little top air, text left-aligned inside it, long paragraphs soft-wrapping at the column edge, and the glamour preview sharing the same column.
+
+**Architecture:** Soft-wrapping is a display-only layer in the `editor` package: logical lines and the logical cursor are unchanged; rendering and vertical navigation become *visual-row* aware. A new `wrap.go` provides word-aware line wrapping, span slicing, and a visual-row builder. The `app` owns layout — it sizes the editor and preview to a computed `contentWidth` and indents their output by a left margin plus a top pad. The picker keeps its full-width split.
+
+**Tech Stack:** Go 1.26, Bubbletea, Bubbles (viewport), Lipgloss, Glamour — already in go.mod.
+
+**Prerequisite:** Build v1.1 (`docs/superpowers/plans/2026-06-28-glint-theme-picker.md`) FIRST. This plan assumes the editor already consumes `theme.Theme` and has `SetTheme`, the app holds an active `theme.Theme` (`a.theme`), and the picker is themed. Do not start this plan until v1.1 is merged.
+
+## Global Constraints
+
+- Module path `glint`; internal packages import as `glint/internal/<pkg>`.
+- **Dependency policy:** newest resolver-selected versions; do not pin or flag versions.
+- **Explicit-foreground invariant:** every rendered span keeps an explicit theme foreground. `sliceSpans` preserves the style of every span it slices — it never emits an unstyled span.
+- **Markup-visible invariant:** soft-wrapping is display-only. The logical buffer is never modified by wrapping; `Bytes()` round-trips the exact logical lines; markup characters stay visible in every visual row.
+- **Layout is rendering-only:** centering margins and top padding are added to the rendered frame, never to the buffer. Saving never inserts margin spaces or wrap breaks.
+- **Wrap partition guarantee:** `wrapLine` segments partition a line's runes contiguously — `concat(segment texts) == line`, no dropped or duplicated runes (the breaking space stays as the trailing rune of its segment).
+- Canvas constants: column ratio `0.65`, max `100`, min `24`, top pad `1`. Column width `= clamp(round(width × 0.65), 24, 100)`, further clamped `≤ width`. Left margin `= (width − contentWidth) / 2`. These are constants — no config keys.
+- Vertical nav: Up/Down move by **visual** row keeping a goal column; Left/Right and Home/End stay **logical**. Scroll is a **visual-row** index.
+- Scope: editor + preview get the canvas; the picker does not. Cursor is a themed cell (no thin-bar). No visual Home/End. No measure config.
+- TDD per task: failing test → run (fails) → implement → run (passes) → commit. Each task ends `go vet ./...` clean and full `go test ./...` green.
+
+---
+
+## File Structure
+
+```
+internal/editor/
+ wrap.go NEW: segment, wrapLine, sliceSpans, vrow, buildVisual, cursorVIndex
+ wrap_test.go NEW: wrap (word/hard/empty/multibyte/partition); sliceSpans boundaries
+ editor.go MOD: goalCol field; visual View; visual MoveUp/MoveDown + applyGoal;
+ visual followCursor; setGoal/visualColOf; setGoal in edit/horizontal ops;
+ themed cursor; SetContent resets goalCol
+ editor_test.go MOD: add visual-wrap nav tests + Bytes round-trip-under-wrap (existing tests stay)
+internal/app/
+ app.go MOD: canvas constants; contentWidth/leftMargin/topPad; setSize sizes
+ editor+preview to contentWidth; View indents+pads editor & preview; picker unindented
+ app_test.go MOD: contentWidth/leftMargin math tests
+```
+
+---
+
+## Task 1: Wrapping utilities (`wrap.go`)
+
+**Files:**
+- Create: `internal/editor/wrap.go`
+- Test: `internal/editor/wrap_test.go`
+
+**Interfaces:**
+- Consumes: `Span` (existing), `ScanLines`, `theme.Theme` (v1.1).
+- Produces:
+ - `segment struct { text string; start int }` (unexported).
+ - `wrapLine(line string, width int) []segment`.
+ - `sliceSpans(spans []Span, start, end int) []Span`.
+ - `vrow struct { logRow, start, runes int; spans []Span }` (unexported).
+ - `(*Editor).buildVisual() []vrow`.
+ - `cursorVIndex(rows []vrow, cur Position) int`.
+
+- [ ] **Step 1: Write the failing tests**
+
+Create `internal/editor/wrap_test.go`:
+```go
+package editor
+
+import (
+ "testing"
+
+ "glint/internal/theme"
+
+ "github.com/charmbracelet/lipgloss"
+)
+
+func segText(segs []segment) string {
+ s := ""
+ for _, sg := range segs {
+ s += sg.text
+ }
+ return s
+}
+
+func TestWrapLineFitsReturnsOneSegment(t *testing.T) {
+ segs := wrapLine("short line", 80)
+ if len(segs) != 1 || segs[0].text != "short line" || segs[0].start != 0 {
+ t.Fatalf("segs = %#v", segs)
+ }
+}
+
+func TestWrapLineEmpty(t *testing.T) {
+ segs := wrapLine("", 80)
+ if len(segs) != 1 || segs[0].text != "" || segs[0].start != 0 {
+ t.Fatalf("empty line segs = %#v", segs)
+ }
+}
+
+func TestWrapLineWordBreakPartition(t *testing.T) {
+ line := "aaaa bbbb cccc"
+ segs := wrapLine(line, 9)
+ if segText(segs) != line {
+ t.Errorf("partition broken: %q != %q", segText(segs), line)
+ }
+ if len(segs) != 2 {
+ t.Fatalf("want 2 segments, got %d: %#v", len(segs), segs)
+ }
+ if segs[0].text != "aaaa " || segs[0].start != 0 {
+ t.Errorf("seg0 = %#v", segs[0])
+ }
+ if segs[1].text != "bbbb cccc" || segs[1].start != 5 {
+ t.Errorf("seg1 = %#v", segs[1])
+ }
+}
+
+func TestWrapLineHardBreaksLongWord(t *testing.T) {
+ segs := wrapLine("abcdefghij", 4)
+ if segText(segs) != "abcdefghij" {
+ t.Errorf("partition broken: %q", segText(segs))
+ }
+ want := []segment{{"abcd", 0}, {"efgh", 4}, {"ij", 8}}
+ if len(segs) != len(want) {
+ t.Fatalf("got %d segments, want %d", len(segs), len(want))
+ }
+ for i := range want {
+ if segs[i] != want[i] {
+ t.Errorf("seg[%d] = %#v, want %#v", i, segs[i], want[i])
+ }
+ }
+}
+
+func TestWrapLineMultibytePartition(t *testing.T) {
+ line := "héllo wörld café"
+ segs := wrapLine(line, 7)
+ if segText(segs) != line {
+ t.Errorf("multibyte partition broken: %q != %q", segText(segs), line)
+ }
+}
+
+func TestSliceSpansAcrossBoundary(t *testing.T) {
+ red := lipgloss.NewStyle().Foreground(lipgloss.Color("#ff0000"))
+ blue := lipgloss.NewStyle().Foreground(lipgloss.Color("#0000ff"))
+ spans := []Span{{Text: "abc", Style: red}, {Text: "def", Style: blue}}
+ out := sliceSpans(spans, 2, 5) // "c" (red) + "de" (blue)
+ got := ""
+ for _, sp := range out {
+ got += sp.Text
+ }
+ if got != "cde" {
+ t.Errorf("sliced text = %q, want cde", got)
+ }
+ if len(out) != 2 || out[0].Style.GetForeground() != lipgloss.Color("#ff0000") ||
+ out[1].Style.GetForeground() != lipgloss.Color("#0000ff") {
+ t.Errorf("styles not preserved: %#v", out)
+ }
+}
+
+func TestBuildVisualAndCursorIndex(t *testing.T) {
+ e := New()
+ e.SetTheme(theme.FlexokiDark())
+ e.Lines = []string{"aaaa bbbb cccc", "x"}
+ e.Width = 9
+ rows := e.buildVisual()
+ // line 0 wraps into 2 visual rows, line 1 is 1 → 3 total.
+ if len(rows) != 3 {
+ t.Fatalf("visual rows = %d, want 3", len(rows))
+ }
+ // cursor at end of seg2 of line 0 maps to the second visual row.
+ if got := cursorVIndex(rows, Position{Row: 0, Col: 10}); got != 1 {
+ t.Errorf("cursorVIndex = %d, want 1", got)
+ }
+ // cursor on line 1 maps to row index 2.
+ if got := cursorVIndex(rows, Position{Row: 1, Col: 0}); got != 2 {
+ t.Errorf("cursorVIndex(line1) = %d, want 2", got)
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/editor/ -run 'TestWrap|TestSliceSpans|TestBuildVisual'`
+Expected: FAIL — `undefined: wrapLine`, `undefined: sliceSpans`, `undefined: buildVisual`.
+
+- [ ] **Step 3: Implement `wrap.go`**
+
+Create `internal/editor/wrap.go`:
+```go
+package editor
+
+// segment is one visual row of a logical line: a contiguous rune slice plus the
+// rune offset (start column) within the logical line where it begins.
+type segment struct {
+ text string
+ start int
+}
+
+// wrapLine word-wraps a logical line into visual segments at the given width.
+// It breaks just after the last space that fits; a word longer than width is
+// hard-broken at width. The segments partition the line's runes contiguously
+// (concatenating their text reproduces the line exactly), so the cursor maps to
+// exactly one segment. A width <= 0 or a line that fits returns one segment; an
+// empty line returns one empty segment.
+func wrapLine(line string, width int) []segment {
+ r := []rune(line)
+ if width <= 0 || len(r) <= width {
+ return []segment{{text: line, start: 0}}
+ }
+ var segs []segment
+ start := 0
+ for start < len(r) {
+ if start+width >= len(r) {
+ segs = append(segs, segment{text: string(r[start:]), start: start})
+ break
+ }
+ end := start + width
+ brk := -1
+ for i := end - 1; i > start; i-- {
+ if r[i] == ' ' {
+ brk = i + 1 // keep the space as this segment's trailing rune
+ break
+ }
+ }
+ if brk <= start {
+ brk = end // long word: hard break
+ }
+ segs = append(segs, segment{text: string(r[start:brk]), start: start})
+ start = brk
+ }
+ if len(segs) == 0 {
+ segs = append(segs, segment{text: "", start: 0})
+ }
+ return segs
+}
+
+// sliceSpans returns the spans covering rune range [start, end) of a line whose
+// spans concatenate to the full line. Boundary spans are split; styles are
+// preserved.
+func sliceSpans(spans []Span, start, end int) []Span {
+ var out []Span
+ pos := 0
+ for _, sp := range spans {
+ r := []rune(sp.Text)
+ spStart, spEnd := pos, pos+len(r)
+ pos = spEnd
+ lo := max(spStart, start)
+ hi := min(spEnd, end)
+ if lo < hi {
+ out = append(out, Span{Text: string(r[lo-spStart : hi-spStart]), Style: sp.Style})
+ }
+ }
+ return out
+}
+
+// vrow is a rendered visual row: which logical row it came from, the rune start
+// offset and rune count within that line, and the styled spans for the segment.
+type vrow struct {
+ logRow int
+ start int
+ runes int
+ spans []Span
+}
+
+// buildVisual wraps every logical line into visual rows, slicing each line's
+// styled spans to the segment ranges.
+func (e *Editor) buildVisual() []vrow {
+ all := ScanLines(e.Lines, e.theme)
+ var rows []vrow
+ for li := range e.Lines {
+ for _, s := range wrapLine(e.Lines[li], e.Width) {
+ n := len([]rune(s.text))
+ rows = append(rows, vrow{
+ logRow: li,
+ start: s.start,
+ runes: n,
+ spans: sliceSpans(all[li], s.start, s.start+n),
+ })
+ }
+ }
+ return rows
+}
+
+// cursorVIndex returns the index of the visual row holding the cursor. A cursor
+// at the end of a line (or on an empty line) maps to that line's last segment.
+func cursorVIndex(rows []vrow, cur Position) int {
+ last := -1
+ for i, vr := range rows {
+ if vr.logRow != cur.Row {
+ continue
+ }
+ last = i
+ if cur.Col >= vr.start && cur.Col < vr.start+vr.runes {
+ return i
+ }
+ }
+ return last
+}
+```
+
+- [ ] **Step 4: Run to verify it passes**
+
+Run: `go test ./internal/editor/ -run 'TestWrap|TestSliceSpans|TestBuildVisual'`
+Expected: PASS.
+
+- [ ] **Step 5: Vet and commit**
+
+```bash
+go vet ./internal/editor/
+git add internal/editor/wrap.go internal/editor/wrap_test.go
+git commit -m "feat: word-aware line wrapping + span slicing + visual rows"
+```
+
+---
+
+## Task 2: Editor visual rendering and navigation
+
+**Files:**
+- Modify: `internal/editor/editor.go`
+- Modify: `internal/editor/editor_test.go`
+
+**Interfaces:**
+- Consumes: `wrapLine`, `buildVisual`, `cursorVIndex`, `sliceSpans` (Task 1).
+- Produces:
+ - `Editor` gains an unexported `goalCol int`.
+ - `View()` renders visual rows with a themed cursor cell.
+ - `MoveUp`/`MoveDown` move by visual row with a preserved goal column.
+ - `Scroll` is a visual-row index; `followCursor` scrolls by visual row.
+ - Horizontal/edit ops set the goal column.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append to `internal/editor/editor_test.go`:
+```go
+func TestVisualDownAndUpAcrossWrappedLine(t *testing.T) {
+ e := New()
+ e.Lines = []string{"aaaa bbbb cccc"} // wraps at width 9 into ["aaaa ","bbbb cccc"]
+ e.SetSize(9, 10)
+ e.Cursor = Position{Row: 0, Col: 0}
+ e.MoveDown() // to the second visual row, goal column 0
+ if e.Cursor != (Position{Row: 0, Col: 5}) {
+ t.Errorf("after MoveDown: %+v, want {0 5}", e.Cursor)
+ }
+ e.MoveUp() // back to the first visual row, goal column 0
+ if e.Cursor != (Position{Row: 0, Col: 0}) {
+ t.Errorf("after MoveUp: %+v, want {0 0}", e.Cursor)
+ }
+}
+
+func TestVisualDownKeepsGoalColumn(t *testing.T) {
+ e := New()
+ e.Lines = []string{"aaaa bbbb cccc"}
+ e.SetSize(9, 10)
+ e.Cursor = Position{Row: 0, Col: 2} // visual column 2 in segment 0
+ e.MoveDown() // segment 1 starts at col 5 → col 5+2 = 7
+ if e.Cursor != (Position{Row: 0, Col: 7}) {
+ t.Errorf("after MoveDown with goal: %+v, want {0 7}", e.Cursor)
+ }
+}
+
+func TestBytesRoundTripUnaffectedByWrap(t *testing.T) {
+ e := New()
+ e.SetContent([]byte("a very long single logical line that will wrap many times\nsecond"))
+ e.SetSize(10, 5)
+ if string(e.Bytes()) != "a very long single logical line that will wrap many times\nsecond" {
+ t.Errorf("wrap altered the buffer: %q", string(e.Bytes()))
+ }
+}
+
+func TestScrollIsVisualRowIndex(t *testing.T) {
+ e := New()
+ e.Lines = []string{"aaaa bbbb cccc dddd eeee ffff"} // one logical line, many visual rows at width 9
+ e.SetSize(9, 2) // only 2 visible visual rows
+ e.Cursor = Position{Row: 0, Col: 0}
+ // Move down several visual rows; Scroll must follow so the cursor stays visible.
+ for i := 0; i < 3; i++ {
+ e.MoveDown()
+ }
+ rows := e.buildVisual()
+ ci := cursorVIndex(rows, e.Cursor)
+ if ci < e.Scroll || ci >= e.Scroll+e.Height {
+ t.Errorf("cursor visual row %d not in viewport [%d,%d)", ci, e.Scroll, e.Scroll+e.Height)
+ }
+}
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/editor/ -run 'TestVisual|TestBytesRoundTripUnaffected|TestScrollIsVisual'`
+Expected: FAIL — `MoveDown` still moves logical rows; `e.goalCol` undefined.
+
+- [ ] **Step 3: Add the `goalCol` field and reset it in `SetContent`**
+
+In `internal/editor/editor.go`, add the field to the `Editor` struct (after `Height int`):
+```go
+ goalCol int // remembered visual column for vertical moves
+```
+In `SetContent`, reset it (add after `e.Scroll = 0`):
+```go
+ e.goalCol = 0
+```
+
+- [ ] **Step 4: Replace `View` with the visual renderer**
+
+Replace the existing `View` method with:
+```go
+// View renders the visible visual rows, styled, with a themed cursor cell on
+// the cursor's visual row. Output is e.Width columns wide; the app adds margins.
+func (e *Editor) View() string {
+ cursorStyle := lipgloss.NewStyle().Foreground(e.theme.Background).Background(e.theme.Pointer)
+ rows := e.buildVisual()
+ ci := cursorVIndex(rows, e.Cursor)
+ var b strings.Builder
+ end := e.Scroll + e.Height
+ if end > len(rows) {
+ end = len(rows)
+ }
+ for r := e.Scroll; r < end; r++ {
+ if r == ci {
+ b.WriteString(renderSpansCursor(rows[r].spans, e.Cursor.Col-rows[r].start, cursorStyle))
+ } else {
+ b.WriteString(renderSpans(rows[r].spans))
+ }
+ b.WriteByte('\n')
+ }
+ for r := end; r < e.Scroll+e.Height; r++ {
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+```
+
+- [ ] **Step 5: Replace `followCursor` with the visual version and add goal helpers**
+
+Replace the existing `followCursor` method with:
+```go
+// followCursor scrolls the viewport so the cursor's visual row stays visible.
+func (e *Editor) followCursor() {
+ rows := e.buildVisual()
+ ci := cursorVIndex(rows, e.Cursor)
+ if ci < 0 {
+ e.Scroll = 0
+ return
+ }
+ if ci < e.Scroll {
+ e.Scroll = ci
+ }
+ if ci >= e.Scroll+e.Height {
+ e.Scroll = ci - e.Height + 1
+ }
+ if e.Scroll < 0 {
+ e.Scroll = 0
+ }
+}
+
+// setGoal records the cursor's current visual column as the goal for vertical moves.
+func (e *Editor) setGoal() { e.goalCol = e.visualColOf(e.Cursor.Row, e.Cursor.Col) }
+
+// visualColOf returns the column of (row, col) within its visual segment.
+func (e *Editor) visualColOf(row, col int) int {
+ segs := wrapLine(e.Lines[row], e.Width)
+ for i := len(segs) - 1; i >= 0; i-- {
+ if col >= segs[i].start {
+ return col - segs[i].start
+ }
+ }
+ return col
+}
+```
+
+- [ ] **Step 6: Replace `MoveUp`/`MoveDown` with visual moves and add `applyGoal`**
+
+Replace the existing `MoveUp` and `MoveDown` methods with:
+```go
+// MoveUp moves to the previous visual row, keeping the goal column.
+func (e *Editor) MoveUp() {
+ rows := e.buildVisual()
+ ci := cursorVIndex(rows, e.Cursor)
+ if ci <= 0 {
+ return
+ }
+ e.applyGoal(rows[ci-1])
+ e.followCursor()
+}
+
+// MoveDown moves to the next visual row, keeping the goal column.
+func (e *Editor) MoveDown() {
+ rows := e.buildVisual()
+ ci := cursorVIndex(rows, e.Cursor)
+ if ci < 0 || ci+1 >= len(rows) {
+ return
+ }
+ e.applyGoal(rows[ci+1])
+ e.followCursor()
+}
+
+// applyGoal places the cursor at the goal column on the given visual row.
+func (e *Editor) applyGoal(target vrow) {
+ e.Cursor.Row = target.logRow
+ e.Cursor.Col = target.start + min(e.goalCol, target.runes)
+}
+```
+
+- [ ] **Step 7: Set the goal column in horizontal and edit ops**
+
+In `internal/editor/editor.go`, add `e.setGoal()` (and `e.followCursor()` where missing) so wrapping and scrolling stay correct. Make these exact edits:
+
+`MoveLeft` — add `e.setGoal()` before the existing `e.followCursor()`:
+```go
+func (e *Editor) MoveLeft() {
+ if e.Cursor.Col > 0 {
+ e.Cursor.Col--
+ } else if e.Cursor.Row > 0 {
+ e.Cursor.Row--
+ e.Cursor.Col = len([]rune(e.Lines[e.Cursor.Row]))
+ }
+ e.setGoal()
+ e.followCursor()
+}
+```
+`MoveRight` — same:
+```go
+func (e *Editor) MoveRight() {
+ if e.Cursor.Col < len(e.curLine()) {
+ e.Cursor.Col++
+ } else if e.Cursor.Row < len(e.Lines)-1 {
+ e.Cursor.Row++
+ e.Cursor.Col = 0
+ }
+ e.setGoal()
+ e.followCursor()
+}
+```
+`MoveHome`/`MoveEnd` — replace the one-liners:
+```go
+func (e *Editor) MoveHome() {
+ e.Cursor.Col = 0
+ e.setGoal()
+ e.followCursor()
+}
+func (e *Editor) MoveEnd() {
+ e.Cursor.Col = len(e.curLine())
+ e.setGoal()
+ e.followCursor()
+}
+```
+`InsertRune` — append `e.setGoal()` and `e.followCursor()` before the closing brace:
+```go
+func (e *Editor) InsertRune(r rune) {
+ rs := e.curLine()
+ col := clamp(e.Cursor.Col, 0, len(rs))
+ rs = append(rs[:col], append([]rune{r}, rs[col:]...)...)
+ e.setLine(rs)
+ e.Cursor.Col = col + 1
+ e.Dirty = true
+ e.setGoal()
+ e.followCursor()
+}
+```
+`InsertNewline` — add `e.setGoal()` right before the existing `e.followCursor()` at the end.
+
+`Backspace` — add `e.setGoal()` and `e.followCursor()` to the within-line branch (which currently returns early without following), and `e.setGoal()` before the existing `e.followCursor()` in the join branch:
+```go
+func (e *Editor) Backspace() {
+ if e.Cursor.Col > 0 {
+ rs := e.curLine()
+ rs = append(rs[:e.Cursor.Col-1], rs[e.Cursor.Col:]...)
+ e.setLine(rs)
+ e.Cursor.Col--
+ e.Dirty = true
+ e.setGoal()
+ e.followCursor()
+ return
+ }
+ if e.Cursor.Row == 0 {
+ return
+ }
+ prev := []rune(e.Lines[e.Cursor.Row-1])
+ joinCol := len(prev)
+ merged := string(prev) + e.Lines[e.Cursor.Row]
+ e.Lines[e.Cursor.Row-1] = merged
+ e.Lines = append(e.Lines[:e.Cursor.Row], e.Lines[e.Cursor.Row+1:]...)
+ e.Cursor.Row--
+ e.Cursor.Col = joinCol
+ e.Dirty = true
+ e.setGoal()
+ e.followCursor()
+}
+```
+`Delete` — add `e.setGoal()` and `e.followCursor()` to the within-line branch and the join branch:
+```go
+func (e *Editor) Delete() {
+ rs := e.curLine()
+ if e.Cursor.Col < len(rs) {
+ rs = append(rs[:e.Cursor.Col], rs[e.Cursor.Col+1:]...)
+ e.setLine(rs)
+ e.Dirty = true
+ e.setGoal()
+ e.followCursor()
+ return
+ }
+ if e.Cursor.Row >= len(e.Lines)-1 {
+ return
+ }
+ e.Lines[e.Cursor.Row] = e.Lines[e.Cursor.Row] + e.Lines[e.Cursor.Row+1]
+ e.Lines = append(e.Lines[:e.Cursor.Row+1], e.Lines[e.Cursor.Row+2:]...)
+ e.Dirty = true
+ e.setGoal()
+ e.followCursor()
+}
+```
+
+- [ ] **Step 8: Run the editor suite**
+
+Run: `go test ./internal/editor/`
+Expected: PASS — the new visual tests plus all v1 tests (the existing movement tests are unaffected because at width 80 the short test lines do not wrap, so visual rows coincide with logical rows).
+
+- [ ] **Step 9: Vet and commit**
+
+```bash
+go vet ./...
+git add internal/editor/editor.go internal/editor/editor_test.go
+git commit -m "feat: visual-row rendering, soft-wrap cursor and scroll in the editor"
+```
+
+---
+
+## Task 3: App canvas layout (centering + padding)
+
+**Files:**
+- Modify: `internal/app/app.go`
+- Modify: `internal/app/app_test.go`
+
+**Interfaces:**
+- Consumes: `(*editor.Editor).SetSize/View`, `(*preview.Model).SetSize/View` (existing).
+- Produces:
+ - Canvas constants and `(*App).contentWidth()`, `(*App).leftMargin()`, `(*App).topPad()`.
+ - `setSize` sizes the editor and preview to `contentWidth`.
+ - `View` indents the editor and preview by the left margin and prepends the top pad; the picker stays full-width.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append to `internal/app/app_test.go`:
+```go
+func TestCanvasContentWidthCapsAndCenters(t *testing.T) {
+ a := newApp()
+ a.Update(tea.WindowSizeMsg{Width: 200, Height: 40})
+ if cw := a.contentWidth(); cw != 100 {
+ t.Errorf("contentWidth = %d, want 100 (capped)", cw)
+ }
+ if lm := a.leftMargin(); lm != (200-100)/2 {
+ t.Errorf("leftMargin = %d, want %d", lm, (200-100)/2)
+ }
+}
+
+func TestCanvasContentWidthFloorsOnNarrow(t *testing.T) {
+ a := newApp()
+ a.Update(tea.WindowSizeMsg{Width: 30, Height: 20})
+ if cw := a.contentWidth(); cw != 24 {
+ t.Errorf("contentWidth = %d, want 24 (floor)", cw)
+ }
+}
+
+func TestCanvasEditorViewIsIndented(t *testing.T) {
+ a := newApp()
+ a.Update(tea.WindowSizeMsg{Width: 120, Height: 20})
+ a.editor.SetContent([]byte("hello"))
+ view := a.View()
+ // The editor body sits in a centered column → at least one rendered line
+ // starts with the left-margin spaces.
+ if a.leftMargin() <= 0 {
+ t.Fatal("expected a positive left margin at width 120")
+ }
+ pad := strings.Repeat(" ", a.leftMargin())
+ found := false
+ for _, ln := range strings.Split(view, "\n") {
+ if strings.HasPrefix(ln, pad) && strings.Contains(ln, "hello") {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("editor content not indented by left margin; view:\n%s", view)
+ }
+}
+```
+Add `"strings"` to the test file's imports if not already present (Task-4 of v1.1 did not require it; add it here).
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `go test ./internal/app/ -run TestCanvas`
+Expected: FAIL — `a.contentWidth` undefined.
+
+- [ ] **Step 3: Add the import and canvas constants/helpers**
+
+In `internal/app/app.go`, add `"math"` to the import block. Add the constants near the top (after the `pendingDiscard` consts):
+```go
+// Canvas layout: a centered, percentage-width text column with a little top air.
+const (
+ canvasRatio = 0.65
+ canvasMax = 100
+ canvasMin = 24
+ canvasTopPad = 1
+)
+```
+Add the helpers (near `setSize`):
+```go
+// contentWidth is the centered text column width: ~65% of the terminal, capped
+// for readability and floored so it never collapses, never wider than the term.
+func (a *App) contentWidth() int {
+ w := int(math.Round(float64(a.width) * canvasRatio))
+ if w > canvasMax {
+ w = canvasMax
+ }
+ if w < canvasMin {
+ w = canvasMin
+ }
+ if w > a.width {
+ w = a.width
+ }
+ return w
+}
+
+// leftMargin centers the content column in the terminal.
+func (a *App) leftMargin() int {
+ m := (a.width - a.contentWidth()) / 2
+ if m < 0 {
+ m = 0
+ }
+ return m
+}
+
+func (a *App) topPad() int { return canvasTopPad }
+
+// indentLines prefixes each non-empty line with n spaces (blank rows stay blank,
+// so the trailing newline of a sub-view does not become a spaces-only row).
+func indentLines(s string, n int) string {
+ if n <= 0 {
+ return s
+ }
+ pad := strings.Repeat(" ", n)
+ lines := strings.Split(s, "\n")
+ for i, ln := range lines {
+ if ln != "" {
+ lines[i] = pad + ln
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+```
+
+- [ ] **Step 4: Size the editor and preview to the content width**
+
+Replace `setSize` with:
+```go
+func (a *App) setSize(w, h int) {
+ a.width = w
+ a.height = h
+ cw := a.contentWidth()
+ textRows := h - 1 - a.topPad() // status bar + top pad
+ if textRows < 1 {
+ textRows = 1
+ }
+ a.editor.SetSize(cw, textRows)
+ a.preview.SetSize(cw, textRows)
+ if a.picker != nil {
+ a.picker.SetSize(w, h-1) // picker keeps its full-width split
+ }
+}
+```
+
+- [ ] **Step 5: Indent and pad the editor/preview in `View`**
+
+Replace `View` with:
+```go
+// View renders the active sub-view. The editor and preview sit in a centered,
+// padded column; the picker keeps its own full-width layout.
+func (a *App) View() string {
+ if a.mode == ModePicker {
+ body := a.picker.View()
+ if !strings.HasSuffix(body, "\n") {
+ body += "\n"
+ }
+ return body + a.statusBar()
+ }
+
+ var body string
+ if a.mode == ModePreview {
+ body = a.preview.View()
+ } else {
+ body = a.editor.View()
+ }
+ body = indentLines(body, a.leftMargin())
+ if a.topPad() > 0 {
+ body = strings.Repeat("\n", a.topPad()) + body
+ }
+ if !strings.HasSuffix(body, "\n") {
+ body += "\n"
+ }
+ return body + a.statusBar()
+}
+```
+
+- [ ] **Step 6: Run app + whole suite, vet, build**
+
+Run: `go test ./internal/app/`
+Expected: PASS.
+
+Run: `go vet ./... && go build ./... && go test ./...`
+Expected: clean, builds, all pass.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add internal/app/
+git commit -m "feat: centered, padded writing canvas for editor and preview"
+```
+
+- [ ] **Step 8: Manual smoke (user-driven, real terminal)**
+
+```bash
+go run . README.md
+```
+Expected: text sits in a centered column with left/right margins and a top gap; a long paragraph soft-wraps at the column edge (word breaks, markup still visible); Up/Down move by visual line through a wrapped paragraph; `Ctrl+R` preview shares the same centered column; `Ctrl+T` still cycles themes; saving round-trips the file unchanged (no inserted line breaks).
+
+---
+
+## Self-Review Notes
+
+**Spec coverage:**
+- A canvas (contentWidth clamp, left margin, top pad, status bar full-width, picker excluded) → Task 3.
+- B.1 word-aware wrapping with partition guarantee, span slicing → Task 1 (`wrapLine`, `sliceSpans`).
+- B.2 visual cursor mapping; Up/Down by visual row with goal column; Left/Right & Home/End logical; visual scroll → Task 2.
+- B.3 visual View with themed cursor cell → Task 2.
+- C preview shares the column → Task 3 (`setSize` sizes preview to contentWidth; `View` indents/pads it).
+- D structure/tests; `Bytes()` round-trip under wrap → Task 2 test.
+- Invariants: explicit foreground (sliceSpans preserves styles), markup-visible/display-only (buffer untouched; round-trip test), layout rendering-only (indent in app View) → Tasks 1–3.
+
+**Type consistency:** `segment`, `vrow`, `wrapLine`, `sliceSpans`, `buildVisual`, `cursorVIndex` defined in Task 1 are used unchanged in Task 2. `e.goalCol`, `e.setGoal`, `e.visualColOf`, `e.applyGoal` introduced in Task 2 are self-contained. App `contentWidth`/`leftMargin`/`topPad`/`indentLines` (Task 3) match their call sites in `setSize`/`View`.
+
+**Known follow-ups (not v1.2 blockers):** visual-row list rebuilt per render/move (no caching) — fine for note-sized files; visual Home/End deferred (logical); true thin-bar cursor not possible in-cell (themed cell instead); the `0.65` ratio and caps are constants, not config.
+```
docs/superpowers/specs/2026-06-28-glint-writing-canvas-design.md +77 −0
@@ -0,0 +1,77 @@
+# glint v1.2 — Writing Canvas (Design)
+
+**Status:** Approved design, pending implementation plan.
+
+**Motivation.** v1 renders text flush against the left edge, full terminal width — it reads like a code editor, not a writing surface. The goal is an iA Writer–style canvas: a centered, comfortably-narrow text column with generous left/right margins and a little top air, text left-aligned inside that column, and long paragraphs that **soft-wrap** at the column edge. Aesthetic target: a mix of a terminal, charm.land, and iA Writer — mono text, near-black on off-white (the `flexoki-light` theme from v1.1), relaxed margins.
+
+This is the **second** v1.x increment. It builds on v1.1 (`docs/superpowers/specs/2026-06-28-glint-theme-picker-design.md`), specifically the themed editor (`editor` already consumes `theme.Theme`). **Sequencing: build v1.1 first, then this.** Both v1.1 and this increment modify `editor` rendering, so doing v1.1 first avoids churn.
+
+## Preserved invariants
+
+1. **Explicit foreground:** every styled span still gets an explicit foreground (unchanged — soft-wrap slices already-styled spans; it never produces an unstyled span).
+2. **Markup-visible:** the scanner still preserves characters exactly. Soft-wrapping is a **display-only** transformation: the logical buffer is untouched, `Bytes()` round-trips the exact logical lines, and the markup characters remain visible in every visual row.
+3. **Layout is rendering-only:** the centering margins and top padding are added to the rendered frame, never to the buffer. Saving a file never inserts margin spaces or wrap breaks.
+
+## A. The canvas (centering + padding)
+
+The app owns layout. Given terminal width `W` and height `H`:
+
+- **Column width (the measure):** `contentWidth = clamp(round(W × 0.65), 24, 100)`, further clamped to `≤ W` for tiny terminals. (Percentage-of-width, capped for readability and floored so it never collapses.)
+- **Left margin:** `(W − contentWidth) / 2`, applied equally on both sides by indenting every rendered content row.
+- **Top padding:** `1` blank row above the content for air.
+- **Status bar:** unchanged — full width, bottom row.
+- The editor and preview are sized to `contentWidth` and rendered into the centered column. The **picker keeps its own full-width split layout** (out of scope for centering).
+
+Row budget: `topPad (1) + textRows + statusBar (1) = H`, so `textRows = H − 2`.
+
+## B. Soft-wrapping editor
+
+The editor keeps its v1 model: logical `Lines []string` and a logical `Cursor{Row, Col}` in rune coordinates; all buffer ops (insert, newline, backspace, delete, left, right) are unchanged and operate on logical coordinates. What changes is **rendering and vertical navigation**, which become *visual-row* aware.
+
+### B.1 Wrapping
+
+- `wrapLine(line, width)` splits a logical line into **segments** (visual rows). It is **word-aware**: it breaks just after the last space that fits within `width`; a word longer than `width` is hard-broken at `width`. An empty line yields one empty segment.
+- **Partition guarantee:** segments partition the line's runes contiguously with no dropped or duplicated characters — `concat(segment texts) == line`. (The breaking space stays as the trailing rune of its segment.) This keeps cursor↔visual mapping exact.
+- A logical line's styled spans (from `ScanLines`) are sliced per segment by rune range, preserving styles (`sliceSpans`).
+
+### B.2 Visual cursor and navigation
+
+- The cursor's **visual position** is the segment of its logical line that contains `Cursor.Col` (the last segment when `Col` is at line end), and the visual column `Col − segment.start`.
+- **Up / Down move by visual row**, not logical row: they target the same **goal visual column** on the adjacent visual row and map it back to logical `{Row, Col}`. The goal column is remembered across consecutive Up/Down and reset whenever the cursor moves horizontally or the buffer changes (standard editor behavior).
+- **Left / Right stay logical** (rune-wise), naturally crossing wrap boundaries and logical line ends — unchanged from v1.
+- **Home / End stay logical** (start / end of the logical line) — unchanged from v1.
+- **Scroll is a visual-row index.** The viewport follows the cursor's visual row, keeping it within `[Scroll, Scroll+Height)`.
+
+### B.3 Rendering
+
+- `View` builds the visual-row list for the buffer, renders the window `[Scroll, Scroll+Height)`, draws the cursor on its visual row at its visual column (themed cursor cell — background `theme.Pointer`, foreground `theme.Background`; a TUI cannot draw iA's thin in-cell bar, so the cell is themed instead), and pads with blank rows to exactly `Height` rows. Output is `contentWidth`-wide (the app adds the left margin).
+
+## C. Preview canvas
+
+`Ctrl+R` glamour preview renders at `contentWidth` (glamour word-wraps to that width) and the app indents it by the same left margin and top padding, so the read view sits in the same column as the editor. The preview's existing viewport scrolling is unchanged.
+
+## D. Structure & testing
+
+```
+internal/editor/
+ wrap.go NEW: segment, wrapLine, sliceSpans, visual-row builder, cursor index
+ wrap_test.go NEW: word/hard wrap, partition guarantee, multibyte, empty line; sliceSpans boundaries
+ editor.go MOD: Width = measure; visual View; visual MoveUp/MoveDown; goalCol; visual followCursor; themed cursor
+ editor_test.go MOD: movement/view tests updated to visual semantics (expected churn)
+internal/app/
+ app.go MOD: contentWidth/leftMargin/topPad; size editor+preview to measure; indent+center editor & preview; picker unchanged
+ app_test.go MOD: a content-width/margin sanity test
+```
+
+- `wrapLine` and `sliceSpans` are pure and carry the high-value unit tests (partition guarantee, word vs hard break, multibyte runes, empty line, span slicing at and across boundaries).
+- Editor visual navigation is tested by constructing a buffer wider than the measure and asserting Down/Up land on the expected logical `{Row, Col}` for a known goal column, and that `Scroll` (visual) follows the cursor.
+- `Bytes()` round-trip test confirms wrapping never alters the buffer.
+- TDD throughout; `go vet ./...`, `go build ./...`, `go test ./...` clean; manual smoke in a real terminal: long paragraphs wrap inside a centered column with margins; Up/Down move visually; `Ctrl+R` preview shares the column.
+
+## E. Out of scope (v1.2)
+
+- Visual Home/End (stay logical).
+- Centering the picker (keeps its split).
+- A true thin-bar cursor (themed cell instead).
+- Configurable measure ratio / margins (the `0.65` ratio and caps are constants).
+- Reflow performance optimization (the visual-row list is rebuilt per render/move; fine for note-sized files, noted as a follow-up).