12345678910111213141516const std = @import("std");17const output = @import("output.zig");1819const PINK = "\x1b[38;2;170;106;82m"; 20const GOLD = "\x1b[38;2;173;138;80m"; 21const MINT = "\x1b[38;2;112;136;129m"; 22const LAV = "\x1b[38;2;122;129;98m"; 2324252627const TEXT = "\x1b[38;2;217;207;195m"; 28const TEXT_DIM = "\x1b[38;2;136;124;113m"; 29const BG_HI = "\x1b[48;2;238;230;219m"; 30const BG_BAR = "\x1b[48;2;205;191;174m"; 31const RESET = "\x1b[0m";32const BOLD = "\x1b[1m";33const DIM = "\x1b[2m";34const INV = "\x1b[7m";35363738fn c(code: []const u8) []const u8 {39 return if (output.colorEnabled()) code else "";40}41424344const Block = union(enum) {45 chapter: []const u8, 46 title: []const u8, 47 badge: []const u8, 48 accent: Accent, 49 para: []const u8, 50 cmd_sig: []const u8, 51 cmd_block: []const u8, 52 flags_row: FlagsRow, 53 callout: Callout, 54 kaomoji_card: KaomojiCard,55 blank,5657 const Accent = enum { gold, mint, pink, lav };5859 const FlagsRow = struct {60 flag: []const u8,61 desc: []const u8,62 };6364 const Callout = struct {65 face: []const u8, 66 body: []const u8,67 color: Accent,68 };6970 const KaomojiCard = struct {71 face: []const u8,72 name: []const u8,73 desc: []const u8,74 when: []const u8,75 color: Accent,76 };77};7879const Section = struct {80 id: []const u8, 81 title: []const u8,82 accent: Block.Accent,83 blocks: []const Block,84};8586878889909192const MAN_PAGE = [_]Section{93 .{94 .id = "intro",95 .title = "what is nina?",96 .accent = .gold,97 .blocks = &[_]Block{98 .{ .para = "nina is a NixOS Intuitive Navigation Assistant — a gentle command-line tool that wraps the full NixOS workflow in one quiet, consistent voice." },99 .{ .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." },100 .{ .para = "written in zig. zero runtime dependencies. a single binary. runs the same on any NixOS machine." },101 .{ .para = "the goal is simple: NixOS should feel like home. nina is one step toward that." },102 .{103 .callout = .{104 .face = "(っ˘ω˘ς)",105 .color = .gold,106 .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.",107 },108 },109 },110 },111 .{112 .id = "install",113 .title = "installation",114 .accent = .gold,115 .blocks = &[_]Block{116 .{ .para = "nina is a nix flake. two ways to install:" },117 .{ .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):" },118 .{ .cmd_block = "experimental-features = nix-command flakes" },119 .{ .para = "or run `nina setup` after installing — she will add the line for you." },120 .{ .para = "direct url (simplest):" },121 .{ .cmd_block = "$ nix profile add 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'" },122 .{ .para = "or build from source with koh:" },123 .{ .cmd_block = "$ koh steal kepr.uk/nina && koh build" },124 .{125 .callout = .{126 .face = "(•̀ᴗ•́)و",127 .color = .mint,128 .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.",129 },130 },131 },132 },133 .{134 .id = "setup",135 .title = "nina setup",136 .accent = .mint,137 .blocks = &[_]Block{138 .{ .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." },139 .{ .cmd_block = "$ nina setup" },140 .{ .para = "on NixOS, nina offers to add this line to /etc/nixos/configuration.nix (keeping a `.nina-bak` backup):" },141 .{ .cmd_block = "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];" },142 .{ .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:" },143 .{ .cmd_block = "$ sudo nixos-rebuild switch" },144 .{ .para = "everywhere else, nina writes `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf. no sudo needed." },145 },146 },147 .{148 .id = "first-run",149 .title = "first run",150 .accent = .gold,151 .blocks = &[_]Block{152 .{ .para = "just type `nina help` at the prompt. she will show you every command she knows. (っ˘ω˘ς)" },153 .{ .para = "then try `nina hello` to see the machines nina has configured, or jump straight to `nina search` to find a package." },154 .{ .para = "from here, search for a package, apply a change, or wander through the tips section to see what is possible." },155 },156 },157 .{158 .id = "search",159 .title = "search & discovery",160 .accent = .mint,161 .blocks = &[_]Block{162 .{ .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." },163 .{ .para = "search nixpkgs for packages in an 18-line inline widget — no fullscreen takeover, no context switch." },164 .{ .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" },165 .{ .para = "search nixpkgs options the same way:" },166 .{ .cmd_block = "$ nina option logind\n:: search options logind N results" },167 .{168 .callout = .{169 .face = "( •̀ω•́ )✧",170 .color = .mint,171 .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",172 },173 },174 },175 },176 .{177 .id = "packages",178 .title = "packages",179 .accent = .lav,180 .blocks = &[_]Block{181 .{ .para = "install packages into your profile with a single command. nina searches nixpkgs, shows you what it found, and asks how you want it." },182 .{ .para = "[i] profile install — runs `nix profile install nixpkgs#attr`. available immediately, no rebuild needed." },183 .{ .para = "[s] system install — opens configuration.nix in your editor at the systemPackages line. add the package, save, and nina asks whether to apply." },184 .{ .para = "[t] try now — drops you into a `nix shell` with the package available. gone when you exit." },185 .{ .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" },186 .{ .para = "explain why a package is installed:" },187 .{ .cmd_block = "$ nina why ripgrep\n:: why ripgrep kyoshi\n\n ripgrep is a direct profile package" },188 .{ .para = "`nina unpin <input>` releases a pinned flake input by running `nix flake update` on it." },189 },190 },191 .{192 .id = "system",193 .title = "system changes",194 .accent = .pink,195 .blocks = &[_]Block{196 .{ .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." },197 .{ .para = "compare two generations using `nix store diff-closures`:" },198 .{ .cmd_block = "$ nina diff\n:: gen 348 -> gen 349 kyoshi\n\n + neovim 0.10.4\n ^ ripgrep 14.0.3 -> 14.1.1" },199 .{ .para = "validate your configuration with `nixos-rebuild build`. catches syntax errors and missing references before they reach a running system." },200 .{ .para = "rebuild and switch to the new generation:" },201 .{ .cmd_block = "$ nina apply\n:: rebuilding kyoshi...\n:: generation 349 [4.1s]" },202 .{ .para = "roll back one generation. to jump to a specific generation, use `nina go <n>`." },203 .{ .cmd_block = "$ nina back\n:: rolling back kyoshi gen 349 -> gen 348\n:: done gen 348" },204 .{205 .flags_row = .{ .flag = "--on <machine>", .desc = "rebuild a remote machine over SSH" },206 },207 .{208 .flags_row = .{ .flag = "--dry", .desc = "dry-activate only — build without switching" },209 },210 .{211 .flags_row = .{ .flag = "--check", .desc = "validate config only, same as `nina check`" },212 },213 .{214 .callout = .{215 .face = "ε-(´∀`; )",216 .color = .pink,217 .body = "generations are immutable snapshots. `nina back` always has somewhere to go, and `nina go <n>` can reach any point in your history.",218 },219 },220 },221 },222 .{223 .id = "flakes",224 .title = "flakes & dev shells",225 .accent = .mint,226 .blocks = &[_]Block{227 .{ .para = "inspect flake outputs, step into dev shells, build specific outputs, and manage the flake lifecycle — all with the same quiet vocabulary." },228 .{ .para = "show what the current directory's flake exposes — packages, apps, dev shells, nixos configurations." },229 .{ .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" },230 .{ .para = "run `nix flake update`. pass a specific input name to update only that one. prints a confirmation when `flake.lock` is written." },231 .{ .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." },232 .{ .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>`." },233 },234 },235 .{236 .id = "inspection",237 .title = "inspection & care",238 .accent = .lav,239 .blocks = &[_]Block{240 .{ .para = "check on the health of your system, follow service logs, inspect the store, and reclaim disk space — without jumping between different tools." },241 .{ .para = "show the current generation and reachability of the target machine:" },242 .{ .cmd_block = "$ nina status\n:: status\n\n kyoshi gen 349 1h ago 10.2 GB\n hm gen 2 2h ago" },243 .{ .para = "run a health diagnostic. checks the nix daemon, config syntax, channels, and home manager." },244 .{ .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" },245 .{ .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." },246 .{ .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." },247 .{ .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." },248 .{ .cmd_block = "$ nina clean\n:: cleaning kyoshi keeping 5 of 14\n continue? [Y/n] y\n:: freed 4.2 GB" },249 },250 },251 .{252 .id = "generations",253 .title = "generation history",254 .accent = .gold,255 .blocks = &[_]Block{256 .{ .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." },257 .{ .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" },258 .{ .para = "switch to any specific generation by number using `nix-env --switch-generation`. use this when `nina back` is not far enough." },259 .{ .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." },260 .{261 .callout = .{262 .face = "(´▽`)",263 .color = .gold,264 .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.",265 },266 },267 },268 },269 .{270 .id = "home",271 .title = "home manager",272 .accent = .lav,273 .blocks = &[_]Block{274 .{ .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." },275 .{ .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." },276 .{ .cmd_block = "$ nina home init --switch\n(っ˘ω˘ς) :: setting up home manager ~/.config/home-manager\n -> will activate after init\n\n(˘ᵕ˘) :: home manager ready" },277 .{ .para = "apply your home manager configuration. runs `home-manager switch` under the hood. `--dry` builds without activating." },278 .{ .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`." },279 .{ .cmd_block = "$ nina home packages\n\n:: home packages kyoshi\n\n hello 2.12.1\n jq 1.7.1" },280 .{281 .callout = .{282 .face = "(っ˘ω˘ς)",283 .color = .lav,284 .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.",285 },286 },287 },288 },289 .{290 .id = "machine-config",291 .title = "machine config",292 .accent = .pink,293 .blocks = &[_]Block{294 .{ .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." },295 .{ .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." },296 .{ .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." },297 .{298 .callout = .{299 .face = "(ˊᗜˋ)",300 .color = .pink,301 .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.",302 },303 },304 },305 },306 .{307 .id = "remote",308 .title = "remote machines",309 .accent = .lav,310 .blocks = &[_]Block{311 .{ .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." },312 .{ .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" },313 .{ .para = "define remote machines in ~/.config/nina/config:" },314 .{ .cmd_block = "[machine]\nname = azula\nhost = june@azula\nssh_key = ~/.ssh/id_ed25519" },315 .{ .para = "fleet commands:" },316 .{317 .flags_row = .{ .flag = "nina hello", .desc = "list all configured machines and their kind (local / ssh)" },318 },319 .{320 .flags_row = .{ .flag = "nina status --on <m>", .desc = "show generation and uptime for a remote machine" },321 },322 .{323 .flags_row = .{ .flag = "nina doctor --on <m>", .desc = "run a full health diagnostic on any machine" },324 },325 .{326 .flags_row = .{ .flag = "nina apply --on <m>", .desc = "rebuild and switch a remote machine over SSH" },327 },328 .{329 .callout = .{330 .face = "(˶ᵔ ᵕ ᵔ˶)",331 .color = .lav,332 .body = "nina keeps remote work from turning into a whole new personality. same verbs, same little reassurances, same sense of where you are.",333 },334 },335 },336 },337 .{338 .id = "hooks",339 .title = "hooks",340 .accent = .mint,341 .blocks = &[_]Block{342 .{ .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." },343 .{ .para = "available hook files:" },344 .{ .cmd_block = "pre-apply post-apply\npre-back post-back\npre-home post-home\npre-upgrade post-upgrade" },345 .{ .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." },346 .{ .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." },347 .{ .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" },348 .{ .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." },349 .{ .para = "example: stop `nina apply` when your nixos config has uncommitted changes." },350 .{ .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" },351 .{ .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." },352 },353 },354 .{355 .id = "configuration",356 .title = "configuration",357 .accent = .gold,358 .blocks = &[_]Block{359 .{ .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. (´ω`)" },360 .{361 .callout = .{362 .face = "(っ˘ω˘ς)",363 .color = .gold,364 .body = "if you have an existing ~/.nina.conf from an earlier version, nina migrates it to ~/.config/nina/config automatically on first run.",365 },366 },367 .{ .para = "full example:" },368 .{ .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" },369 .{ .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." },370 .{ .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`." },371 },372 },373 .{374 .id = "expressions",375 .title = "expressions ♡",376 .accent = .pink,377 .blocks = &[_]Block{378 .{ .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." },379 .{ .para = "the rule is simple: calm most of the time, brighter when something lands, softer when something goes wrong." },380 .{381 .kaomoji_card = .{382 .face = "(˶ᵔ ᵕ ᵔ˶)",383 .name = "hello",384 .color = .lav,385 .desc = "a warm, quiet welcome. nina is ready to help and not making a fuss about it.",386 .when = "setup wizard, first-run greeting",387 },388 },389 .{390 .kaomoji_card = .{391 .face = "(っ˘ω˘ς)",392 .name = "starting",393 .color = .mint,394 .desc = "settling in and getting to work. something meaningful is beginning.",395 .when = "apply start, home apply start, entering a dev shell",396 },397 },398 .{399 .kaomoji_card = .{400 .face = "╰(*°▽°*)╯",401 .name = "relief",402 .color = .gold,403 .desc = "something that was broken is working again. a small celebration for persistence.",404 .when = "first success after a previously failed build",405 },406 },407 .{408 .kaomoji_card = .{409 .face = "( ˘ᵕ˘ )",410 .name = "done",411 .color = .lav,412 .desc = "calm satisfaction. a rollback landed cleanly and the system is in good hands.",413 .when = "back success",414 },415 },416 .{417 .kaomoji_card = .{418 .face = "( ´ ∀ ` )",419 .name = "clean",420 .color = .mint,421 .desc = "light and tidy. the work is done and things look better than before.",422 .when = "clean done",423 },424 },425 .{426 .kaomoji_card = .{427 .face = "( ´ ▽ ` )",428 .name = "all good",429 .color = .gold,430 .desc = "everything checked out. a quiet joy that the system is healthy.",431 .when = "doctor all clear, mood all good",432 },433 },434 .{435 .kaomoji_card = .{436 .face = "(˘ω˘ )",437 .name = "exiting",438 .color = .lav,439 .desc = "a gentle close. nothing went wrong — it's just time to step out.",440 .when = "try exit, leaving a dev shell",441 },442 },443 .{444 .kaomoji_card = .{445 .face = "(;ω;)",446 .name = "sorry",447 .color = .pink,448 .desc = "something went sideways, and nina is honest about it. details are right there with her.",449 .when = "network or SSH errors, search timeout",450 },451 },452 .{453 .callout = .{454 .face = "( ´•̥̥̥ω•̥̥̥` )",455 .color = .pink,456 .body = "if you prefer a quieter experience, set `color = false` in your config. nina will still show everything — just without the ansi palette.",457 },458 },459 },460 },461 .{462 .id = "tips",463 .title = "tips & recipes",464 .accent = .mint,465 .blocks = &[_]Block{466 .{ .para = "a few patterns that make daily nixos life a little smoother. (*˘︶˘*)" },467 .{ .para = "a quiet morning with nina:" },468 .{ .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" },469 .{ .para = "try a package without committing to it:" },470 .{ .cmd_block = "$ nina try bat\n:: trying bat exit when done\n → bat is available in this shell only, gone when you exit" },471 .{ .para = "push the same config change to multiple machines:" },472 .{ .cmd_block = "$ nina apply --on kyoshi\n:: generation 349 [4.1s]\n$ nina apply --on azula\n:: generation 193 [6.3s]" },473 .{ .para = "something broke and you want to find when:" },474 .{ .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" },475 .{ .para = "useful shell aliases:" },476 .{ .cmd_block = "alias ns=\"nina search\"\nalias no=\"nina option\"\nalias na=\"nina apply\"\nalias nd=\"nina diff\"\nalias nb=\"nina back\"" },477 .{478 .callout = .{479 .face = "(≧◡≦)",480 .color = .mint,481 .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.",482 },483 },484 },485 },486};487488489490491492493494var PAGE_ROWS: u16 = 22;495const MIN_PAGE_ROWS: u16 = 5;496const COL_WIDTH: u16 = 96; 497498499500const HEADER_ROWS: u16 = 3;501const FOOTER_ROWS: u16 = 1;502fn frameRows() u16 {503 return HEADER_ROWS + PAGE_ROWS + FOOTER_ROWS;504}505506507508509fn detectPageRows(io: std.Io) u16 {510 var ws: std.posix.winsize = .{ .row = 0, .col = 0, .xpixel = 0, .ypixel = 0 };511 const result = io.operate(.{ .device_io_control = .{512 .file = std.Io.File.stdout(),513 .code = std.posix.T.IOCGWINSZ,514 .arg = &ws,515 } }) catch return PAGE_ROWS;516 if (result.device_io_control < 0) return PAGE_ROWS;517 if (ws.row <= HEADER_ROWS + FOOTER_ROWS + MIN_PAGE_ROWS) return PAGE_ROWS;518 return ws.row - HEADER_ROWS - FOOTER_ROWS;519}520521pub fn run(io: std.Io, topic: []const u8) !void {522 523 524 if (!(std.Io.File.stdout().isTty(io) catch false)) {525 return runPlain(io, topic);526 }527528 529 var saved: std.posix.termios = undefined;530 try rawModeEnable(STDIN_FD, &saved);531 defer rawModeDisable(STDIN_FD, saved);532533 PAGE_ROWS = detectPageRows(io);534535 const start_section: usize = if (topic.len == 0) 0 else blk: {536 for (MAN_PAGE, 0..) |sec, i| {537 if (std.mem.eql(u8, sec.id, topic)) break :blk i;538 }539 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });540 output.flush();541 return;542 };543544 545 546 547 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);548 defer arena.deinit();549 const allocator = arena.allocator();550551 var rendered = std.ArrayList([]const u8).empty;552 defer rendered.deinit(allocator);553554 555 556 var section_starts = std.ArrayList(usize).empty;557 defer section_starts.deinit(allocator);558 var section_titles = std.ArrayList([]const u8).empty;559 defer section_titles.deinit(allocator);560561 try section_starts.append(allocator, 0);562 for (MAN_PAGE) |sec| {563 try section_titles.append(allocator, sec.title);564 try renderSection(allocator, &rendered, sec);565 try section_starts.append(allocator, rendered.items.len);566 }567 const total: usize = rendered.items.len;568569 var top: usize = 0;570 var cur_section: usize = start_section;571 top = section_starts.items[start_section];572573 drawHeader();574 drawBody(rendered.items, top, total, section_titles.items, cur_section);575 drawFooter(cur_section, MAN_PAGE.len, top, total);576 output.flush();577578 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};579 while (true) {580 _ = std.posix.poll(&pfd, -1) catch break;581582 var buf: [8]u8 = undefined;583 const n = std.posix.read(STDIN_FD, &buf) catch break;584 if (n == 0) break;585586 const advance_section = struct {587 fn f(starts: []const usize, cur: usize, delta: i32) usize {588 var idx: i32 = @intCast(cur);589 idx += delta;590 if (idx < 0) idx = 0;591 if (idx >= @as(i32, @intCast(starts.len - 1))) idx = @intCast(starts.len - 2);592 return starts[@intCast(idx)];593 }594 }.f;595596 597 const sectionOf = struct {598 fn f(starts: []usize, t: usize) usize {599 var s: usize = 0;600 for (starts[1..], 1..) |start, i| {601 if (t < start) return i - 1;602 s = i;603 }604 return s;605 }606 }.f;607608 var redraw = true;609 if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {610 switch (buf[2]) {611 'A' => top = if (top > 0) top - 1 else 0, 612 'B' => top = if (top + 1 < total) top + 1 else top, 613 'C' => top = advance_section(section_starts.items, cur_section, 1), 614 'D' => top = advance_section(section_starts.items, cur_section, -1), 615 '5' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0, 616 '6' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1, 617 'H' => top = 0, 618 'F' => top = if (total > 0) total - 1 else 0, 619 else => redraw = false,620 }621 } else switch (buf[0]) {622 'q', 'Q', 0x1b => break, 623 'j' => top = if (top + 1 < total) top + 1 else top,624 'k' => top = if (top > 0) top - 1 else 0,625 ' ' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1,626 'b' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0,627 'g' => top = 0,628 'G' => top = if (total > 0) total - 1 else 0,629 'n' => top = advance_section(section_starts.items, cur_section, 1),630 'p' => top = advance_section(section_starts.items, cur_section, -1),631 'h' => top = 0,632 '?' => {633 showHelp();634 redraw = false;635 },636 else => redraw = false,637 }638639 if (redraw) {640 cur_section = sectionOf(section_starts.items, top);641 642 643 644 645 output.cursorUp(PAGE_ROWS + FOOTER_ROWS);646 drawBody(rendered.items, top, total, section_titles.items, cur_section);647 drawFooter(cur_section, MAN_PAGE.len, top, total);648 output.flush();649 }650 }651652 653 654 655 output.cursorUp(frameRows());656 for (0..frameRows()) |_| {657 output.raw("\x1b[K\n");658 }659 output.cursorUp(frameRows());660 output.flush();661}662663fn runPlain(_: std.Io, topic: []const u8) !void {664 const start_section: usize = if (topic.len == 0) 0 else blk: {665 for (MAN_PAGE, 0..) |sec, i| {666 if (std.mem.eql(u8, sec.id, topic)) break :blk i;667 }668 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });669 output.flush();670 return;671 };672673 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);674 defer arena.deinit();675 const allocator = arena.allocator();676677 var rendered = std.ArrayList([]const u8).empty;678 defer rendered.deinit(allocator);679680 var i: usize = start_section;681 while (i < MAN_PAGE.len) : (i += 1) {682 try renderSection(allocator, &rendered, MAN_PAGE[i]);683 }684 for (rendered.items) |line| output.raw(line);685 output.raw("\n");686 output.flush();687}688689const STDIN_FD = std.posix.STDIN_FILENO;690691fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void {692 var tio = try std.posix.tcgetattr(fd);693 saved.* = tio;694 695 696 697 698 699 tio.lflag.ECHO = false;700 tio.lflag.ICANON = false;701 tio.lflag.ISIG = false;702 tio.lflag.IEXTEN = false;703 tio.iflag.ICRNL = false;704 tio.iflag.IXON = false;705 tio.cc[@intFromEnum(std.posix.V.MIN)] = 1;706 tio.cc[@intFromEnum(std.posix.V.TIME)] = 0;707 try std.posix.tcsetattr(fd, .FLUSH, tio);708}709710fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void {711 std.posix.tcsetattr(fd, .FLUSH, saved) catch {};712}713714715716const AccentColor = struct {717 fg: []const u8,718 bar: []const u8,719};720721fn accentColors(a: Block.Accent) AccentColor {722 return switch (a) {723 .gold => .{ .fg = GOLD, .bar = GOLD },724 .mint => .{ .fg = MINT, .bar = MINT },725 .pink => .{ .fg = PINK, .bar = PINK },726 .lav => .{ .fg = LAV, .bar = LAV },727 };728}729730fn renderSection(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), sec: Section) !void {731 732 var idx_buf: [16]u8 = undefined;733 const idx_str = std.fmt.bufPrint(&idx_buf, "{d:0>2}", .{sectionIndexOf(sec.id) + 1}) catch "00";734735 const accent = accentColors(sec.accent);736 const divider = try std.fmt.allocPrint(allocator, "{s}── {s}{s}{s} {s}{s}{s}\n", .{737 c(TEXT_DIM),738 c(accent.fg), sec.title, c(RESET),739 c(TEXT_DIM), idx_str, c(RESET),740 });741 try out.append(allocator, divider);742743 for (sec.blocks) |block| {744 try renderBlock(allocator, out, block);745 }746747 748 try out.append(allocator, "\n");749}750751fn sectionIndexOf(id: []const u8) usize {752 for (MAN_PAGE, 0..) |sec, i| {753 if (std.mem.eql(u8, sec.id, id)) return i;754 }755 return 0;756}757758fn renderBlock(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), block: Block) !void {759 switch (block) {760 .chapter => try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s} {s}{s}\n\n", .{ c(TEXT_DIM), block.chapter, c(RESET), "" })),761 .title => {762 const accent = accentColors(block.accent);763 const padded_title = try std.fmt.allocPrint(allocator, " {s}◆{s} {s}{s}{s} ", .{ c(accent.bar), c(RESET), c(BOLD), block.title, c(RESET) });764 try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s}\n", .{ padded_title, "" }));765 if (block.badge.len > 0) {766 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) }));767 }768 },769 .badge => {}, 770 .accent => {}, 771 .para => {772 const wrapped = try wrap(allocator, block.para, COL_WIDTH);773 for (wrapped) |line| {774 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(TEXT), line, c(RESET) }));775 }776 },777 .cmd_sig => {778 const accent = accentColors(block.accent);779 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) }));780 },781 .cmd_block => {782 const wrapped = try wrap(allocator, block.cmd_block, COL_WIDTH);783 for (wrapped) |line| {784 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(MINT), line, c(RESET) }));785 }786 try out.append(allocator, "\n");787 },788 .flags_row => {789 const accent = accentColors(.gold);790 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) }));791 },792 .callout => {793 const accent = accentColors(block.callout.color);794 const wrapped = try wrap(allocator, block.callout.body, COL_WIDTH - 6);795 var first = true;796 for (wrapped) |line| {797 if (first) {798 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) }));799 first = false;800 } else {801 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) }));802 }803 }804 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└─{s}\n", .{ c(accent.bar), c(RESET) }));805 },806 .kaomoji_card => {807 const accent = accentColors(block.kaomoji_card.color);808 809 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) }));810 const desc_lines = try wrap(allocator, block.kaomoji_card.desc, COL_WIDTH - 10);811 for (desc_lines) |line| {812 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) }));813 }814 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) }));815 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└──{s}\n", .{ c(accent.bar), c(RESET) }));816 },817 .blank => try out.append(allocator, "\n"),818 }819}820821822fn wrap(allocator: std.mem.Allocator, text: []const u8, width: u16) ![]const []const u8 {823 var lines = std.ArrayList([]const u8).empty;824 errdefer lines.deinit(allocator);825826 var it = std.mem.splitScalar(u8, text, '\n');827 while (it.next()) |para| {828 if (para.len == 0) {829 try lines.append(allocator, "");830 continue;831 }832 var start: usize = 0;833 while (start < para.len) {834 var end = @min(start + @as(usize, width), para.len);835 if (end < para.len) {836 var back: usize = end;837 while (back > start and para[back - 1] != ' ') : (back -= 1) {}838 if (back > start) end = back;839 }840 try lines.append(allocator, std.mem.trim(u8, para[start..end], " \t"));841 start = end;842 while (start < para.len and para[start] == ' ') : (start += 1) {}843 }844 }845 return lines.toOwnedSlice(allocator);846}847848849850fn drawHeader() void {851 852 output.raw("\x1b[K");853 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) });854 output.raw("\x1b[K");855 output.p("{s} {s}(˶ᵔ ᵕ ᵔ˶){s} ready when you are{s}\n", .{ c(BG_HI), c(PINK), c(RESET), c(RESET) });856 output.raw("\x1b[K");857 output.p("{s}{s}{s}\n", .{ c(TEXT_DIM), "─" ** 80, c(RESET) });858}859860fn drawBody(lines: []const []const u8, top: usize, total: usize, titles: []const []const u8, cur_section: usize) void {861 _ = total;862 _ = titles;863 _ = cur_section;864 865 866 867 868 869 var i: usize = 0;870 while (i < PAGE_ROWS) : (i += 1) {871 output.raw("\x1b[K");872 const idx = top + i;873 if (idx < lines.len) {874 output.raw(lines[idx]);875 } else {876 output.raw("\n");877 }878 }879}880881fn drawFooter(cur_section: usize, total_sections: usize, top: usize, total: usize) void {882 const pct: usize = if (total == 0) 0 else (top * 100) / total;883 output.raw("\x1b[K");884 var sec_buf: [16]u8 = undefined;885 const sec_str = std.fmt.bufPrint(&sec_buf, "{d}", .{cur_section + 1}) catch "?";886 var tot_buf: [16]u8 = undefined;887 const tot_str = std.fmt.bufPrint(&tot_buf, "{d}", .{total_sections}) catch "?";888 var pct_buf: [16]u8 = undefined;889 const pct_str = std.fmt.bufPrint(&pct_buf, "{d}", .{pct}) catch "?";890 output.p("{s}{s}─── {s}{s:>2}/{s}{s} {s}{s:>3}%{s} {s}· ↑↓ scroll · n/p next/prev section · q quit{s}\n", .{891 c(TEXT_DIM), c(BG_HI),892 c(MINT), sec_str, tot_str, c(RESET),893 c(GOLD), pct_str, c(RESET),894 c(TEXT_DIM), c(RESET),895 });896}897898fn showHelp() void {899 output.cursorUp(frameRows());900 for (0..frameRows()) |_| output.raw("\x1b[K\n");901 output.cursorUp(frameRows());902 drawHeader();903 drawHelpBody();904 drawFooter(0, MAN_PAGE.len, 0, 1);905 output.flush();906907 908 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};909 _ = std.posix.poll(&pfd, -1) catch {};910 var buf: [8]u8 = undefined;911 _ = std.posix.read(STDIN_FD, &buf) catch {};912}913914fn drawHelpBody() void {915 const pairs = [_]struct { key: []const u8, desc: []const u8 }{916 .{ .key = "j / ↓", .desc = "scroll down one line" },917 .{ .key = "k / ↑", .desc = "scroll up one line" },918 .{ .key = "space", .desc = "page down" },919 .{ .key = "b / pgup", .desc = "page up" },920 .{ .key = "g / home", .desc = "jump to top" },921 .{ .key = "G / end", .desc = "jump to bottom" },922 .{ .key = "n / →", .desc = "next section" },923 .{ .key = "p / ←", .desc = "previous section" },924 .{ .key = "h", .desc = "back to top (table of contents)" },925 .{ .key = "?", .desc = "this help" },926 .{ .key = "q / esc", .desc = "leave the manpage" },927 };928 var i: usize = 0;929 while (i < PAGE_ROWS) : (i += 1) {930 output.raw("\x1b[K");931 if (i == 0) {932 output.p(" {s}{s}nina man · keys{s}\n\n", .{ c(BOLD), c(PINK), c(RESET) });933 } else if (i - 1 < pairs.len) {934 const p = pairs[i - 1];935 output.p(" {s}{s:<14}{s} {s}{s}{s}\n", .{ c(GOLD), p.key, c(RESET), c(TEXT), p.desc, c(RESET) });936 } else {937 output.raw("\n");938 }939 }940}