12345678910111213141516const std = @import("std");17const output = @import("output.zig");18const rawterm = @import("rawterm.zig");1920const PINK = "\x1b[38;2;170;106;82m"; 21const GOLD = "\x1b[38;2;173;138;80m"; 22const MINT = "\x1b[38;2;112;136;129m"; 23const LAV = "\x1b[38;2;122;129;98m"; 2425262728const TEXT = "\x1b[38;2;217;207;195m"; 29const TEXT_DIM = "\x1b[38;2;136;124;113m"; 30const BG_HI = "\x1b[48;2;238;230;219m"; 31const BG_BAR = "\x1b[48;2;205;191;174m"; 32const RESET = "\x1b[0m";33const BOLD = "\x1b[1m";34const DIM = "\x1b[2m";35const INV = "\x1b[7m";36373839fn c(code: []const u8) []const u8 {40 return if (output.colorEnabled()) code else "";41}42434445const Block = union(enum) {46 chapter: []const u8, 47 title: []const u8, 48 badge: []const u8, 49 accent: Accent, 50 para: []const u8, 51 cmd_sig: []const u8, 52 cmd_block: []const u8, 53 flags_row: FlagsRow, 54 callout: Callout, 55 kaomoji_card: KaomojiCard,56 blank,5758 const Accent = enum { gold, mint, pink, lav };5960 const FlagsRow = struct {61 flag: []const u8,62 desc: []const u8,63 };6465 const Callout = struct {66 face: []const u8, 67 body: []const u8,68 color: Accent,69 };7071 const KaomojiCard = struct {72 face: []const u8,73 name: []const u8,74 desc: []const u8,75 when: []const u8,76 color: Accent,77 };78};7980const Section = struct {81 id: []const u8, 82 title: []const u8,83 accent: Block.Accent,84 blocks: []const Block,85};8687888990919293const MAN_PAGE = [_]Section{94 .{95 .id = "intro",96 .title = "what is nina?",97 .accent = .gold,98 .blocks = &[_]Block{99 .{ .para = "nina is a NixOS Intuitive Navigation Assistant — a gentle command-line tool that wraps the full NixOS workflow in one quiet, consistent voice." },100 .{ .para = "she handles package search, rebuilds, flakes, services, generation history, and remote machines — all without dropping you into a different screen, switching tools, or making you memorise long nixos-rebuild incantations." },101 .{ .para = "written in zig. zero runtime dependencies. a single binary. runs the same on any NixOS machine." },102 .{ .para = "the goal is simple: NixOS should feel like home. nina is one step toward that." },103 .{104 .callout = .{105 .face = "(っ˘ω˘ς)",106 .color = .gold,107 .body = "nina stays inline at your prompt. search results, install confirmations, diff previews — everything comes to you. you never leave the shell you're already in.",108 },109 },110 },111 },112 .{113 .id = "install",114 .title = "installation",115 .accent = .gold,116 .blocks = &[_]Block{117 .{ .para = "nina is a nix flake. two ways to install:" },118 .{ .para = "both methods require nix-command and flakes to be enabled. add this to ~/.config/nix/nix.conf (or /etc/nix/nix.conf on NixOS):" },119 .{ .cmd_block = "experimental-features = nix-command flakes" },120 .{ .para = "or run `nina setup` after installing — she will add the line for you." },121 .{ .para = "direct url (simplest):" },122 .{ .cmd_block = "$ nix profile add 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'" },123 .{ .para = "or build from source with koh:" },124 .{ .cmd_block = "$ koh steal kepr.uk/nina && koh build" },125 .{126 .callout = .{127 .face = "(•̀ᴗ•́)و",128 .color = .mint,129 .body = "after installing, run `nina setup` — it makes sure the nix features nina needs are turned on, and on NixOS walks you through the one config line.",130 },131 },132 },133 },134 .{135 .id = "setup",136 .title = "nina setup",137 .accent = .mint,138 .blocks = &[_]Block{139 .{ .para = "`nina setup` is your onboarding step. it makes sure nix's experimental features are enabled, which is all nina needs to search and install packages. if they're already on, it prints `all set` and exits." },140 .{ .cmd_block = "$ nina setup" },141 .{ .para = "on NixOS, nina offers to add this line to /etc/nixos/configuration.nix (keeping a `.nina-bak` backup):" },142 .{ .cmd_block = "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];" },143 .{ .para = "press y and nina appends it for you. press n and nina shows you the line to paste. either way it ends with one step:" },144 .{ .cmd_block = "$ sudo nixos-rebuild switch" },145 .{ .para = "everywhere else, nina writes `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf. no sudo needed." },146 },147 },148 .{149 .id = "first-run",150 .title = "first run",151 .accent = .gold,152 .blocks = &[_]Block{153 .{ .para = "just type `nina help` at the prompt. she will show you every command she knows. (っ˘ω˘ς)" },154 .{ .para = "then try `nina hello` to see the machines nina has configured, or jump straight to `nina search` to find a package." },155 .{ .para = "from here, search for a package, apply a change, or wander through the tips section to see what is possible." },156 },157 },158 .{159 .id = "search",160 .title = "search & discovery",161 .accent = .mint,162 .blocks = &[_]Block{163 .{ .para = "inline search that never takes over your screen. results appear right below the prompt, and you navigate them with the keyboard. press esc any time to go back to what you were doing." },164 .{ .para = "search nixpkgs for packages in an 18-line inline widget — no fullscreen takeover, no context switch." },165 .{ .cmd_block = "$ nina search ripgrep\n:: search nixpkgs ripgrep 3 results\n\n ripgrep 14.1.0 recursively search directories\n ripgrep-all 0.10.0 ripgrep, but also search in PDFs\n ripgrep-fixed 0.1.0 ripgrep with fixed-string matching\n\n ↓↑ navigate · i install · s system · t try · esc" },166 .{ .para = "search nixpkgs options the same way:" },167 .{ .cmd_block = "$ nina option logind\n:: search options logind N results" },168 .{169 .callout = .{170 .face = "( •̀ω•́ )✧",171 .color = .mint,172 .body = "keys: ↓↑ or j k move through results · i or Enter profile install · s system install · t try · c copy attr · Esc or q exit",173 },174 },175 },176 },177 .{178 .id = "packages",179 .title = "packages",180 .accent = .lav,181 .blocks = &[_]Block{182 .{ .para = "install packages into your profile with a single command. nina searches nixpkgs, shows you what it found, and asks how you want it." },183 .{ .para = "[i] profile install — runs `nix profile install nixpkgs#attr`. available immediately, no rebuild needed." },184 .{ .para = "[s] system install — opens configuration.nix in your editor at the systemPackages line. add the package, save, and nina asks whether to apply." },185 .{ .para = "[t] try now — drops you into a `nix shell` with the package available. gone when you exit." },186 .{ .cmd_block = "$ nina install neovim\n:: neovim 0.10.4\n\n [i] profile install instant no rebuild\n [s] system install opens editor requires apply\n [t] try now exits when done\n\n > i\n:: installing neovim profile\n -> nix profile install nixpkgs#neovim\n:: neovim installed available now" },187 .{ .para = "explain why a package is installed:" },188 .{ .cmd_block = "$ nina why ripgrep\n:: why ripgrep kyoshi\n\n ripgrep is a direct profile package" },189 .{ .para = "`nina unpin <input>` releases a pinned flake input by running `nix flake update` on it." },190 },191 },192 .{193 .id = "system",194 .title = "system changes",195 .accent = .pink,196 .blocks = &[_]Block{197 .{ .para = "preview, apply, and roll back changes to your nixos system. nina shows you exactly what will change before it happens, and arms a rollback the moment things go sideways." },198 .{ .para = "compare two generations using `nix store diff-closures`:" },199 .{ .cmd_block = "$ nina diff\n:: gen 348 -> gen 349 kyoshi\n\n + neovim 0.10.4\n ^ ripgrep 14.0.3 -> 14.1.1" },200 .{ .para = "validate your configuration with `nixos-rebuild build`. catches syntax errors and missing references before they reach a running system." },201 .{ .para = "rebuild and switch to the new generation:" },202 .{ .cmd_block = "$ nina apply\n:: rebuilding kyoshi...\n:: generation 349 [4.1s]" },203 .{ .para = "roll back one generation. to jump to a specific generation, use `nina go <n>`." },204 .{ .cmd_block = "$ nina back\n:: rolling back kyoshi gen 349 -> gen 348\n:: done gen 348" },205 .{206 .flags_row = .{ .flag = "--on <machine>", .desc = "rebuild a remote machine over SSH" },207 },208 .{209 .flags_row = .{ .flag = "--dry", .desc = "dry-activate only — build without switching" },210 },211 .{212 .flags_row = .{ .flag = "--check", .desc = "validate config only, same as `nina check`" },213 },214 .{215 .callout = .{216 .face = "ε-(´∀`; )",217 .color = .pink,218 .body = "generations are immutable snapshots. `nina back` always has somewhere to go, and `nina go <n>` can reach any point in your history.",219 },220 },221 },222 },223 .{224 .id = "flakes",225 .title = "flakes & dev shells",226 .accent = .mint,227 .blocks = &[_]Block{228 .{ .para = "inspect flake outputs, step into dev shells, build specific outputs, and manage the flake lifecycle — all with the same quiet vocabulary." },229 .{ .para = "show what the current directory's flake exposes — packages, apps, dev shells, nixos configurations." },230 .{ .cmd_block = "$ nina flake show\n:: .\n\n packages x86_64-linux nina\n apps x86_64-linux nina\n devShells x86_64-linux default" },231 .{ .para = "run `nix flake update`. pass a specific input name to update only that one. prints a confirmation when `flake.lock` is written." },232 .{ .para = "enter the flake's dev shell with `nix develop`. type `exit` to return. `develop run <cmd>` runs a single command without an interactive shell." },233 .{ .para = "build a flake output with `nix build`. result is linked as `./result`. run a package without installing it — bare names are resolved as `nixpkgs#<pkg>`." },234 },235 },236 .{237 .id = "inspection",238 .title = "inspection & care",239 .accent = .lav,240 .blocks = &[_]Block{241 .{ .para = "check on the health of your system, follow service logs, inspect the store, and reclaim disk space — without jumping between different tools." },242 .{ .para = "show the current generation and reachability of the target machine:" },243 .{ .cmd_block = "$ nina status\n:: status\n\n kyoshi gen 349 1h ago 10.2 GB\n hm gen 2 2h ago" },244 .{ .para = "run a health diagnostic. checks the nix daemon, config syntax, channels, and home manager." },245 .{ .cmd_block = "$ nina doctor\n:: diagnosing kyoshi\n\n nix daemon ok\n config syntax ok\n channel ok\n home manager standalone gen 2\n\n:: all good" },246 .{ .para = "manage systemd services. `service logs <name> -f` follows the journal live. `stop` and `disable` prompt for confirmation when `confirm = true`. all service commands accept `--user` to target user-managed services." },247 .{ .para = "inspect and maintain the nix store. `store info` shows total size, live paths, and reclaimable space. `store gc` runs garbage collection. `store path <attr>` evaluates a store path for a nixpkgs attribute." },248 .{ .para = "remove old generations and run garbage collection. keeps the number of generations set by `generations` in your config (default: 5). `--all` removes all old generations regardless." },249 .{ .cmd_block = "$ nina clean\n:: cleaning kyoshi keeping 5 of 14\n continue? [Y/n] y\n:: freed 4.2 GB" },250 },251 },252 .{253 .id = "generations",254 .title = "generation history",255 .accent = .gold,256 .blocks = &[_]Block{257 .{ .para = "your system's whole story is saved in generations. browse them, compare them, travel back to any of them. nothing is gone until you clean it up." },258 .{ .cmd_block = "$ nina history\n:: generations kyoshi\n\n 349 2026-05-30 09:32:01 current\n 348 2026-05-29 14:22:44\n 347 2026-05-25 11:05:33" },259 .{ .para = "switch to any specific generation by number using `nix-env --switch-generation`. use this when `nina back` is not far enough." },260 .{ .para = "show nina's operation log from ~/.local/share/nina/nina.log. displays the last 50 entries by default. use `--last N` to show more or fewer." },261 .{262 .callout = .{263 .face = "(´▽`)",264 .color = .gold,265 .body = "generations are your safety net. apply freely, knowing you can always go back. `nina history` shows the whole story. `nina go` takes you there.",266 },267 },268 },269 },270 .{271 .id = "home",272 .title = "home manager",273 .accent = .lav,274 .blocks = &[_]Block{275 .{ .para = "nina manages your home manager configuration with the same vocabulary as your system. all `nina home` commands work with standalone home manager and NixOS module setups. nina detects which mode you're using automatically." },276 .{ .para = "bootstrap home manager for the first time. runs `nix run home-manager/<branch> -- init`, which creates ~/.config/home-manager/home.nix with a starter configuration. passing `--switch` activates the configuration immediately." },277 .{ .cmd_block = "$ nina home init --switch\n(っ˘ω˘ς) :: setting up home manager ~/.config/home-manager\n -> will activate after init\n\n(˘ᵕ˘) :: home manager ready" },278 .{ .para = "apply your home manager configuration. runs `home-manager switch` under the hood. `--dry` builds without activating." },279 .{ .para = "roll back to the previous home manager generation. list home generations. show what changed between the last two with `home diff`. validate without applying with `home check`. open `home.nix` with `home edit`." },280 .{ .cmd_block = "$ nina home packages\n\n:: home packages kyoshi\n\n hello 2.12.1\n jq 1.7.1" },281 .{282 .callout = .{283 .face = "(っ˘ω˘ς)",284 .color = .lav,285 .body = "the same apply → diff → back pattern works for your home config, just as it does for your system. nina uses the same verbs so you do not have to learn a second vocabulary.",286 },287 },288 },289 },290 .{291 .id = "machine-config",292 .title = "machine config",293 .accent = .pink,294 .blocks = &[_]Block{295 .{ .para = "edit your configuration safely, inspect the running system, manage channels, and set boot defaults — all without needing to remember the right file path or nixos-rebuild flag." },296 .{ .para = "open configuration.nix in your configured editor (default: vim). pass `hardware` to open hardware-configuration.nix instead. after saving, run `nina check` to validate before applying." },297 .{ .para = "format configuration.nix with `nixpkgs-fmt`. `--check` reports whether formatting is needed without writing. show the nixos version, kernel version, and uptime of the target machine. list boot entries from the bootloader. launch `nix repl` with nixpkgs loaded." },298 .{299 .callout = .{300 .face = "(ˊᗜˋ)",301 .color = .pink,302 .body = "`nina edit` uses the `editor` value from ~/.config/nina/config (default: vim). set it to your editor of choice and nina will use it everywhere.",303 },304 },305 },306 },307 .{308 .id = "remote",309 .title = "remote machines",310 .accent = .lav,311 .blocks = &[_]Block{312 .{ .para = "the same voice, even over SSH. every nina command accepts `--on <machine>` and behaves identically on a remote host. no separate tooling, no context switching." },313 .{ .cmd_block = "$ nina apply --on azula\n ✦ rebuilding azula over ssh\n · building generation 193\n generation 193.\n\n$ nina service logs ollama -f --on azula\n ✦ following logs for ollama on azula\n [info] serving on 0.0.0.0:11434" },314 .{ .para = "define remote machines in ~/.config/nina/config:" },315 .{ .cmd_block = "[machine]\nname = azula\nhost = june@azula\nssh_key = ~/.ssh/id_ed25519" },316 .{ .para = "fleet commands:" },317 .{318 .flags_row = .{ .flag = "nina hello", .desc = "list all configured machines and their kind (local / ssh)" },319 },320 .{321 .flags_row = .{ .flag = "nina status --on <m>", .desc = "show generation and uptime for a remote machine" },322 },323 .{324 .flags_row = .{ .flag = "nina doctor --on <m>", .desc = "run a full health diagnostic on any machine" },325 },326 .{327 .flags_row = .{ .flag = "nina apply --on <m>", .desc = "rebuild and switch a remote machine over SSH" },328 },329 .{330 .callout = .{331 .face = "(˶ᵔ ᵕ ᵔ˶)",332 .color = .lav,333 .body = "nina keeps remote work from turning into a whole new personality. same verbs, same little reassurances, same sense of where you are.",334 },335 },336 },337 },338 .{339 .id = "hooks",340 .title = "hooks",341 .accent = .mint,342 .blocks = &[_]Block{343 .{ .para = "nina can run optional executable scripts before and after state-changing commands. hooks live in ~/.config/nina/hooks/. missing hooks are ignored, and files that are not executable are treated as absent." },344 .{ .para = "available hook files:" },345 .{ .cmd_block = "pre-apply post-apply\npre-back post-back\npre-home post-home\npre-upgrade post-upgrade" },346 .{ .para = "`pre-apply` runs before `nina apply`, `pre-back` before `nina back`, `pre-home` before `nina home apply`, and `pre-upgrade` before `nina upgrade`. the matching `post-*` hooks run only after the command succeeds." },347 .{ .para = "if a pre-hook exits non-zero, nina shows the exit code and the last five lines of hook output, then asks whether to continue. that prompt defaults to no." },348 .{ .cmd_block = ":: pre-apply hook exited with code 1\n\n uncommitted changes - commit before applying\n\n continue anyway? [y/N] n\n:: aborted" },349 .{ .para = "if a post-hook fails, nina prints a warning after the success line. the original command already succeeded, so the hook warning does not turn the operation into a failure." },350 .{ .para = "example: stop `nina apply` when your nixos config has uncommitted changes." },351 .{ .cmd_block = "#!/usr/bin/env sh\n# ~/.config/nina/hooks/pre-apply\nif git -C ~/nixos-config status --porcelain | grep -q .; then\n echo \"uncommitted changes - commit before applying\"\n exit 1\nfi" },352 .{ .para = "make hook scripts executable with `chmod +x ~/.config/nina/hooks/pre-apply`. nina creates the hooks directory automatically the first time it checks for hooks." },353 },354 },355 .{356 .id = "configuration",357 .title = "configuration",358 .accent = .gold,359 .blocks = &[_]Block{360 .{ .para = "nina's config file lives at ~/.config/nina/config (XDG). the format is plain key=value, one per line. comments start with #. all settings are optional — nina works out of the box with no config file. (´ω`)" },361 .{362 .callout = .{363 .face = "(っ˘ω˘ς)",364 .color = .gold,365 .body = "if you have an existing ~/.nina.conf from an earlier version, nina migrates it to ~/.config/nina/config automatically on first run.",366 },367 },368 .{ .para = "full example:" },369 .{ .cmd_block = "editor = nvim\ngenerations = 5\nconfirm = true\nteach = false\ncolor = true\n\n[machine]\nname = kyoshi\nconfig = /etc/nixos\nlocal = true\ndefault = true\n\n[machine]\nname = azula\nhost = june@azula\nssh_key = ~/.ssh/id_ed25519" },370 .{ .para = "if you have a [machine] host set, `local` automatically becomes false and `nina --on azula` runs everything over SSH. `default = true` on a machine block selects it when no `--on` is given." },371 .{ .para = "every config key accepts the values you'd expect. booleans read true / false / yes / no. integers are decimal. `~` in `ssh_key` expands to `$HOME`." },372 },373 },374 .{375 .id = "expressions",376 .title = "expressions ♡",377 .accent = .pink,378 .blocks = &[_]Block{379 .{ .para = "nina uses a few small kaomoji expressions instead of a mascot. they stay tucked into the UI, show a little feeling, and leave the work itself readable." },380 .{ .para = "the rule is simple: calm most of the time, brighter when something lands, softer when something goes wrong." },381 .{382 .kaomoji_card = .{383 .face = "(˶ᵔ ᵕ ᵔ˶)",384 .name = "hello",385 .color = .lav,386 .desc = "a warm, quiet welcome. nina is ready to help and not making a fuss about it.",387 .when = "setup wizard, first-run greeting",388 },389 },390 .{391 .kaomoji_card = .{392 .face = "(っ˘ω˘ς)",393 .name = "starting",394 .color = .mint,395 .desc = "settling in and getting to work. something meaningful is beginning.",396 .when = "apply start, home apply start, entering a dev shell",397 },398 },399 .{400 .kaomoji_card = .{401 .face = "╰(*°▽°*)╯",402 .name = "relief",403 .color = .gold,404 .desc = "something that was broken is working again. a small celebration for persistence.",405 .when = "first success after a previously failed build",406 },407 },408 .{409 .kaomoji_card = .{410 .face = "( ˘ᵕ˘ )",411 .name = "done",412 .color = .lav,413 .desc = "calm satisfaction. a rollback landed cleanly and the system is in good hands.",414 .when = "back success",415 },416 },417 .{418 .kaomoji_card = .{419 .face = "( ´ ∀ ` )",420 .name = "clean",421 .color = .mint,422 .desc = "light and tidy. the work is done and things look better than before.",423 .when = "clean done",424 },425 },426 .{427 .kaomoji_card = .{428 .face = "( ´ ▽ ` )",429 .name = "all good",430 .color = .gold,431 .desc = "everything checked out. a quiet joy that the system is healthy.",432 .when = "doctor all clear, mood all good",433 },434 },435 .{436 .kaomoji_card = .{437 .face = "(˘ω˘ )",438 .name = "exiting",439 .color = .lav,440 .desc = "a gentle close. nothing went wrong — it's just time to step out.",441 .when = "try exit, leaving a dev shell",442 },443 },444 .{445 .kaomoji_card = .{446 .face = "(;ω;)",447 .name = "sorry",448 .color = .pink,449 .desc = "something went sideways, and nina is honest about it. details are right there with her.",450 .when = "network or SSH errors, search timeout",451 },452 },453 .{454 .callout = .{455 .face = "( ´•̥̥̥ω•̥̥̥` )",456 .color = .pink,457 .body = "if you prefer a quieter experience, set `color = false` in your config. nina will still show everything — just without the ansi palette.",458 },459 },460 },461 },462 .{463 .id = "tips",464 .title = "tips & recipes",465 .accent = .mint,466 .blocks = &[_]Block{467 .{ .para = "a few patterns that make daily nixos life a little smoother. (*˘︶˘*)" },468 .{ .para = "a quiet morning with nina:" },469 .{ .cmd_block = "# update flake inputs and preview changes\n$ nina flake update\n$ nina diff\n\n# apply if the diff looks good\n$ nina apply" },470 .{ .para = "try a package without committing to it:" },471 .{ .cmd_block = "$ nina try bat\n:: trying bat exit when done\n → bat is available in this shell only, gone when you exit" },472 .{ .para = "push the same config change to multiple machines:" },473 .{ .cmd_block = "$ nina apply --on kyoshi\n:: generation 349 [4.1s]\n$ nina apply --on azula\n:: generation 193 [6.3s]" },474 .{ .para = "something broke and you want to find when:" },475 .{ .cmd_block = "$ nina history\n → find the last known-good generation number\n$ nina diff 344 349\n → see what changed across those generations\n$ nina go 344\n:: done gen 344" },476 .{ .para = "useful shell aliases:" },477 .{ .cmd_block = "alias ns=\"nina search\"\nalias no=\"nina option\"\nalias na=\"nina apply\"\nalias nd=\"nina diff\"\nalias nb=\"nina back\"" },478 .{479 .callout = .{480 .face = "(≧◡≦)",481 .color = .mint,482 .body = "when something goes wrong, `nina back` is always there. when you're not sure what to try next, `nina diff` shows you the picture. and when things go right, nina keeps the terminal feeling light.",483 },484 },485 },486 },487};488489490491492493494495var PAGE_ROWS: u16 = 22;496const MIN_PAGE_ROWS: u16 = 5;497const COL_WIDTH: u16 = 96; 498499500501const HEADER_ROWS: u16 = 3;502const FOOTER_ROWS: u16 = 1;503fn frameRows() u16 {504 return HEADER_ROWS + PAGE_ROWS + FOOTER_ROWS;505}506507508509510fn detectPageRows(io: std.Io) u16 {511 var ws: std.posix.winsize = .{ .row = 0, .col = 0, .xpixel = 0, .ypixel = 0 };512 const result = io.operate(.{ .device_io_control = .{513 .file = std.Io.File.stdout(),514 .code = std.posix.T.IOCGWINSZ,515 .arg = &ws,516 } }) catch return PAGE_ROWS;517 if (result.device_io_control < 0) return PAGE_ROWS;518 if (ws.row <= HEADER_ROWS + FOOTER_ROWS + MIN_PAGE_ROWS) return PAGE_ROWS;519 return ws.row - HEADER_ROWS - FOOTER_ROWS;520}521522pub fn run(io: std.Io, topic: []const u8) !void {523 524 525 if (!(std.Io.File.stdout().isTty(io) catch false)) {526 return runPlain(io, topic);527 }528529 530 var saved: std.posix.termios = undefined;531 try rawterm.rawModeEnable(STDIN_FD, &saved);532 defer rawterm.rawModeDisable(STDIN_FD, saved);533534 PAGE_ROWS = detectPageRows(io);535536 const start_section: usize = if (topic.len == 0) 0 else blk: {537 for (MAN_PAGE, 0..) |sec, i| {538 if (std.mem.eql(u8, sec.id, topic)) break :blk i;539 }540 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });541 output.flush();542 return;543 };544545 546 547 548 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);549 defer arena.deinit();550 const allocator = arena.allocator();551552 var rendered = std.ArrayList([]const u8).empty;553 defer rendered.deinit(allocator);554555 556 557 var section_starts = std.ArrayList(usize).empty;558 defer section_starts.deinit(allocator);559 var section_titles = std.ArrayList([]const u8).empty;560 defer section_titles.deinit(allocator);561562 try section_starts.append(allocator, 0);563 for (MAN_PAGE) |sec| {564 try section_titles.append(allocator, sec.title);565 try renderSection(allocator, &rendered, sec);566 try section_starts.append(allocator, rendered.items.len);567 }568 const total: usize = rendered.items.len;569570 var top: usize = 0;571 var cur_section: usize = start_section;572 top = section_starts.items[start_section];573574 drawHeader();575 drawBody(rendered.items, top, total, section_titles.items, cur_section);576 drawFooter(cur_section, MAN_PAGE.len, top, total);577 output.flush();578579 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};580 while (true) {581 _ = std.posix.poll(&pfd, -1) catch break;582583 var buf: [8]u8 = undefined;584 const n = std.posix.read(STDIN_FD, &buf) catch break;585 if (n == 0) break;586587 const advance_section = struct {588 fn f(starts: []const usize, cur: usize, delta: i32) usize {589 var idx: i32 = @intCast(cur);590 idx += delta;591 if (idx < 0) idx = 0;592 if (idx >= @as(i32, @intCast(starts.len - 1))) idx = @intCast(starts.len - 2);593 return starts[@intCast(idx)];594 }595 }.f;596597 598 const sectionOf = struct {599 fn f(starts: []usize, t: usize) usize {600 var s: usize = 0;601 for (starts[1..], 1..) |start, i| {602 if (t < start) return i - 1;603 s = i;604 }605 return s;606 }607 }.f;608609 var redraw = true;610 if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {611 switch (buf[2]) {612 'A' => top = if (top > 0) top - 1 else 0, 613 'B' => top = if (top + 1 < total) top + 1 else top, 614 'C' => top = advance_section(section_starts.items, cur_section, 1), 615 'D' => top = advance_section(section_starts.items, cur_section, -1), 616 '5' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0, 617 '6' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1, 618 'H' => top = 0, 619 'F' => top = if (total > 0) total - 1 else 0, 620 else => redraw = false,621 }622 } else switch (buf[0]) {623 'q', 'Q', 0x1b => break, 624 'j' => top = if (top + 1 < total) top + 1 else top,625 'k' => top = if (top > 0) top - 1 else 0,626 ' ' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1,627 'b' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0,628 'g' => top = 0,629 'G' => top = if (total > 0) total - 1 else 0,630 'n' => top = advance_section(section_starts.items, cur_section, 1),631 'p' => top = advance_section(section_starts.items, cur_section, -1),632 'h' => top = 0,633 '?' => {634 showHelp();635 636 637 638 639 redraw = true;640 },641 else => redraw = false,642 }643644 if (redraw) {645 cur_section = sectionOf(section_starts.items, top);646 647 648 649 650 output.cursorUp(PAGE_ROWS + FOOTER_ROWS);651 drawBody(rendered.items, top, total, section_titles.items, cur_section);652 drawFooter(cur_section, MAN_PAGE.len, top, total);653 output.flush();654 }655 }656657 658 659 660 output.cursorUp(frameRows());661 for (0..frameRows()) |_| {662 output.raw("\x1b[K\n");663 }664 output.cursorUp(frameRows());665 output.flush();666}667668fn runPlain(_: std.Io, topic: []const u8) !void {669 const start_section: usize = if (topic.len == 0) 0 else blk: {670 for (MAN_PAGE, 0..) |sec, i| {671 if (std.mem.eql(u8, sec.id, topic)) break :blk i;672 }673 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });674 output.flush();675 return;676 };677678 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);679 defer arena.deinit();680 const allocator = arena.allocator();681682 var rendered = std.ArrayList([]const u8).empty;683 defer rendered.deinit(allocator);684685 var i: usize = start_section;686 while (i < MAN_PAGE.len) : (i += 1) {687 try renderSection(allocator, &rendered, MAN_PAGE[i]);688 }689 for (rendered.items) |line| output.raw(line);690 output.raw("\n");691 output.flush();692}693694const STDIN_FD = rawterm.STDIN_FD;695696697698699700701702const AccentColor = struct {703 fg: []const u8,704 bar: []const u8,705};706707fn accentColors(a: Block.Accent) AccentColor {708 return switch (a) {709 .gold => .{ .fg = GOLD, .bar = GOLD },710 .mint => .{ .fg = MINT, .bar = MINT },711 .pink => .{ .fg = PINK, .bar = PINK },712 .lav => .{ .fg = LAV, .bar = LAV },713 };714}715716fn renderSection(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), sec: Section) !void {717 718 var idx_buf: [16]u8 = undefined;719 const idx_str = std.fmt.bufPrint(&idx_buf, "{d:0>2}", .{sectionIndexOf(sec.id) + 1}) catch "00";720721 const accent = accentColors(sec.accent);722 const divider = try std.fmt.allocPrint(allocator, "{s}── {s}{s}{s} {s}{s}{s}\n", .{723 c(TEXT_DIM),724 c(accent.fg), sec.title, c(RESET),725 c(TEXT_DIM), idx_str, c(RESET),726 });727 try out.append(allocator, divider);728729 for (sec.blocks) |block| {730 try renderBlock(allocator, out, block);731 }732733 734 try out.append(allocator, "\n");735}736737fn sectionIndexOf(id: []const u8) usize {738 for (MAN_PAGE, 0..) |sec, i| {739 if (std.mem.eql(u8, sec.id, id)) return i;740 }741 return 0;742}743744fn renderBlock(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), block: Block) !void {745 switch (block) {746 .chapter => try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s} {s}{s}\n\n", .{ c(TEXT_DIM), block.chapter, c(RESET), "" })),747 .title => {748 const accent = accentColors(block.accent);749 const padded_title = try std.fmt.allocPrint(allocator, " {s}◆{s} {s}{s}{s} ", .{ c(accent.bar), c(RESET), c(BOLD), block.title, c(RESET) });750 try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s}\n", .{ padded_title, "" }));751 if (block.badge.len > 0) {752 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}[{s}{s}{s}{s}]{s}\n", .{ c(TEXT_DIM), c(accent.fg), block.badge, c(TEXT_DIM), c(RESET), c(RESET) }));753 }754 },755 .badge => {}, 756 .accent => {}, 757 .para => {758 const wrapped = try wrap(allocator, block.para, COL_WIDTH);759 for (wrapped) |line| {760 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(TEXT), line, c(RESET) }));761 }762 },763 .cmd_sig => {764 const accent = accentColors(block.accent);765 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}│{s} {s}{s}{s}\n", .{ c(accent.fg), c(RESET), c(accent.fg), block.cmd_sig, c(RESET) }));766 },767 .cmd_block => {768 const wrapped = try wrap(allocator, block.cmd_block, COL_WIDTH);769 for (wrapped) |line| {770 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(MINT), line, c(RESET) }));771 }772 try out.append(allocator, "\n");773 },774 .flags_row => {775 const accent = accentColors(.gold);776 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}│{s} {s}{s:<22}{s} {s}{s}{s}\n", .{ c(accent.fg), c(RESET), c(accent.fg), block.flags_row.flag, c(RESET), c(TEXT), block.flags_row.desc, c(RESET) }));777 },778 .callout => {779 const accent = accentColors(block.callout.color);780 const wrapped = try wrap(allocator, block.callout.body, COL_WIDTH - 6);781 var first = true;782 for (wrapped) |line| {783 if (first) {784 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}┌─ {s}{s} {s}{s}{s}\n", .{ c(accent.bar), c(accent.fg), block.callout.face, c(TEXT), line, c(RESET) }));785 first = false;786 } else {787 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}│{s} {s}{s}{s}\n", .{ c(accent.bar), c(RESET), c(TEXT), line, c(RESET) }));788 }789 }790 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└─{s}\n", .{ c(accent.bar), c(RESET) }));791 },792 .kaomoji_card => {793 const accent = accentColors(block.kaomoji_card.color);794 795 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}┌── {s}{s} {s}{s}{s}\n", .{ c(accent.bar), c(accent.fg), block.kaomoji_card.face, c(BOLD), block.kaomoji_card.name, c(RESET) }));796 const desc_lines = try wrap(allocator, block.kaomoji_card.desc, COL_WIDTH - 10);797 for (desc_lines) |line| {798 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}│{s} {s}{s}{s}\n", .{ c(accent.bar), c(RESET), c(TEXT), line, c(RESET) }));799 }800 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}│{s} {s}when:{s} {s}{s}{s}\n", .{ c(accent.bar), c(RESET), c(TEXT_DIM), c(RESET), c(TEXT_DIM), block.kaomoji_card.when, c(RESET) }));801 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└──{s}\n", .{ c(accent.bar), c(RESET) }));802 },803 .blank => try out.append(allocator, "\n"),804 }805}806807808fn wrap(allocator: std.mem.Allocator, text: []const u8, width: u16) ![]const []const u8 {809 var lines = std.ArrayList([]const u8).empty;810 errdefer lines.deinit(allocator);811812 var it = std.mem.splitScalar(u8, text, '\n');813 while (it.next()) |para| {814 if (para.len == 0) {815 try lines.append(allocator, "");816 continue;817 }818 var start: usize = 0;819 while (start < para.len) {820 var end = @min(start + @as(usize, width), para.len);821 if (end < para.len) {822 var back: usize = end;823 while (back > start and para[back - 1] != ' ') : (back -= 1) {}824 if (back > start) end = back;825 }826 try lines.append(allocator, std.mem.trim(u8, para[start..end], " \t"));827 start = end;828 while (start < para.len and para[start] == ' ') : (start += 1) {}829 }830 }831 return lines.toOwnedSlice(allocator);832}833834835836fn drawHeader() void {837 838 output.raw("\x1b[K");839 output.p("{s}{s} nina man {s}the whole picture · press ? for keys · q to leave{s}\n", .{ c(BG_BAR), c(PINK), c(TEXT), c(RESET) });840 output.raw("\x1b[K");841 output.p("{s} {s}(˶ᵔ ᵕ ᵔ˶){s} ready when you are{s}\n", .{ c(BG_HI), c(PINK), c(RESET), c(RESET) });842 output.raw("\x1b[K");843 output.p("{s}{s}{s}\n", .{ c(TEXT_DIM), "─" ** 80, c(RESET) });844}845846fn drawBody(lines: []const []const u8, top: usize, total: usize, titles: []const []const u8, cur_section: usize) void {847 _ = total;848 _ = titles;849 _ = cur_section;850 851 852 853 854 855 var i: usize = 0;856 while (i < PAGE_ROWS) : (i += 1) {857 output.raw("\x1b[K");858 const idx = top + i;859 if (idx < lines.len) {860 output.raw(lines[idx]);861 } else {862 output.raw("\n");863 }864 }865}866867fn drawFooter(cur_section: usize, total_sections: usize, top: usize, total: usize) void {868 const pct: usize = if (total == 0) 0 else (top * 100) / total;869 output.raw("\x1b[K");870 var sec_buf: [16]u8 = undefined;871 const sec_str = std.fmt.bufPrint(&sec_buf, "{d}", .{cur_section + 1}) catch "?";872 var tot_buf: [16]u8 = undefined;873 const tot_str = std.fmt.bufPrint(&tot_buf, "{d}", .{total_sections}) catch "?";874 var pct_buf: [16]u8 = undefined;875 const pct_str = std.fmt.bufPrint(&pct_buf, "{d}", .{pct}) catch "?";876 output.p("{s}{s}─── {s}{s:>2}/{s}{s} {s}{s:>3}%{s} {s}· ↑↓ scroll · n/p next/prev section · q quit{s}\n", .{877 c(TEXT_DIM), c(BG_HI),878 c(MINT), sec_str, tot_str, c(RESET),879 c(GOLD), pct_str, c(RESET),880 c(TEXT_DIM), c(RESET),881 });882}883884fn showHelp() void {885 output.cursorUp(frameRows());886 for (0..frameRows()) |_| output.raw("\x1b[K\n");887 output.cursorUp(frameRows());888 drawHeader();889 drawHelpBody();890 drawFooter(0, MAN_PAGE.len, 0, 1);891 output.flush();892893 894 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};895 _ = std.posix.poll(&pfd, -1) catch {};896 var buf: [8]u8 = undefined;897 _ = std.posix.read(STDIN_FD, &buf) catch {};898}899900fn drawHelpBody() void {901 const pairs = [_]struct { key: []const u8, desc: []const u8 }{902 .{ .key = "j / ↓", .desc = "scroll down one line" },903 .{ .key = "k / ↑", .desc = "scroll up one line" },904 .{ .key = "space", .desc = "page down" },905 .{ .key = "b / pgup", .desc = "page up" },906 .{ .key = "g / home", .desc = "jump to top" },907 .{ .key = "G / end", .desc = "jump to bottom" },908 .{ .key = "n / →", .desc = "next section" },909 .{ .key = "p / ←", .desc = "previous section" },910 .{ .key = "h", .desc = "back to top (table of contents)" },911 .{ .key = "?", .desc = "this help" },912 .{ .key = "q / esc", .desc = "leave the manpage" },913 };914 915 916 917 918 919 920 921 var i: usize = 0;922 while (i < PAGE_ROWS) : (i += 1) {923 output.raw("\x1b[K");924 if (i == 0) {925 output.p(" {s}{s}nina man · keys{s}\n", .{ c(BOLD), c(PINK), c(RESET) });926 } else if (i - 1 < pairs.len) {927 const p = pairs[i - 1];928 output.p(" {s}{s:<14}{s} {s}{s}{s}\n", .{ c(GOLD), p.key, c(RESET), c(TEXT), p.desc, c(RESET) });929 } else {930 output.raw("\n");931 }932 }933}934935936937938939940941942943944945fn newlineCount(bytes: []const u8) usize {946 return std.mem.count(u8, bytes, "\n");947}948949test "drawHelpBody emits exactly PAGE_ROWS rows regardless of PAGE_ROWS' value" {950 const saved_page_rows = PAGE_ROWS;951 defer PAGE_ROWS = saved_page_rows;952953 var writer: std.Io.Writer.Allocating = .init(std.testing.allocator);954 defer writer.deinit();955 var env: std.process.Environ.Map = .init(std.testing.allocator);956 defer env.deinit();957 output.init(&writer.writer, std.testing.io, &env, false);958959 for ([_]u16{ 5, 12, MIN_PAGE_ROWS }) |rows| {960 PAGE_ROWS = rows;961 writer.clearRetainingCapacity();962 drawHelpBody();963 try std.testing.expectEqual(@as(usize, rows), newlineCount(writer.written()));964 }965}966967test "drawBody emits exactly PAGE_ROWS rows" {968 const saved_page_rows = PAGE_ROWS;969 defer PAGE_ROWS = saved_page_rows;970 PAGE_ROWS = 6;971972 var writer: std.Io.Writer.Allocating = .init(std.testing.allocator);973 defer writer.deinit();974 var env: std.process.Environ.Map = .init(std.testing.allocator);975 defer env.deinit();976 output.init(&writer.writer, std.testing.io, &env, false);977978 const lines = [_][]const u8{ "one\n", "two\n", "three\n" };979 drawBody(&lines, 0, lines.len, &.{}, 0);980981 try std.testing.expectEqual(@as(usize, PAGE_ROWS), newlineCount(writer.written()));982}