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 = "pin or unpin a flake input to a specific commit. `nina unpin` runs `nix flake update` on that input to release the pin." },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};487488489490const PAGE_ROWS: u16 = 22; 491const COL_WIDTH: u16 = 96; 492493494495const HEADER_ROWS: u16 = 3;496const FOOTER_ROWS: u16 = 1;497const FRAME_ROWS: u16 = HEADER_ROWS + PAGE_ROWS + FOOTER_ROWS;498499pub fn run(io: std.Io, topic: []const u8) !void {500 501 502 if (!(std.Io.File.stdout().isTty(io) catch false)) {503 return runPlain(io, topic);504 }505506 507 var saved: std.posix.termios = undefined;508 try rawModeEnable(STDIN_FD, &saved);509 defer rawModeDisable(STDIN_FD, saved);510511 const start_section: usize = if (topic.len == 0) 0 else blk: {512 for (MAN_PAGE, 0..) |sec, i| {513 if (std.mem.eql(u8, sec.id, topic)) break :blk i;514 }515 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });516 output.flush();517 return;518 };519520 521 522 523 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);524 defer arena.deinit();525 const allocator = arena.allocator();526527 var rendered = std.ArrayList([]const u8).empty;528 defer rendered.deinit(allocator);529530 531 532 var section_starts = std.ArrayList(usize).empty;533 defer section_starts.deinit(allocator);534 var section_titles = std.ArrayList([]const u8).empty;535 defer section_titles.deinit(allocator);536537 try section_starts.append(allocator, 0);538 for (MAN_PAGE) |sec| {539 try section_titles.append(allocator, sec.title);540 try renderSection(allocator, &rendered, sec);541 try section_starts.append(allocator, rendered.items.len);542 }543 const total: usize = rendered.items.len;544545 var top: usize = 0;546 var cur_section: usize = start_section;547 top = section_starts.items[start_section];548549 drawHeader();550 drawBody(rendered.items, top, total, section_titles.items, cur_section);551 drawFooter(cur_section, MAN_PAGE.len, top, total);552 output.flush();553554 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};555 while (true) {556 _ = std.posix.poll(&pfd, -1) catch break;557558 var buf: [8]u8 = undefined;559 const n = std.posix.read(STDIN_FD, &buf) catch break;560 if (n == 0) break;561562 const advance_section = struct {563 fn f(starts: []const usize, cur: usize, delta: i32) usize {564 var idx: i32 = @intCast(cur);565 idx += delta;566 if (idx < 0) idx = 0;567 if (idx >= @as(i32, @intCast(starts.len - 1))) idx = @intCast(starts.len - 2);568 return starts[@intCast(idx)];569 }570 }.f;571572 573 const sectionOf = struct {574 fn f(starts: []usize, t: usize) usize {575 var s: usize = 0;576 for (starts[1..], 1..) |start, i| {577 if (t < start) return i - 1;578 s = i;579 }580 return s;581 }582 }.f;583584 var redraw = true;585 if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {586 switch (buf[2]) {587 'A' => top = if (top > 0) top - 1 else 0, 588 'B' => top = if (top + 1 < total) top + 1 else top, 589 'C' => top = advance_section(section_starts.items, cur_section, 1), 590 'D' => top = advance_section(section_starts.items, cur_section, -1), 591 '5' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0, 592 '6' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1, 593 'H' => top = 0, 594 'F' => top = if (total > 0) total - 1 else 0, 595 else => redraw = false,596 }597 } else switch (buf[0]) {598 'q', 'Q', 0x1b => break, 599 'j' => top = if (top + 1 < total) top + 1 else top,600 'k' => top = if (top > 0) top - 1 else 0,601 ' ' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1,602 'b' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0,603 'g' => top = 0,604 'G' => top = if (total > 0) total - 1 else 0,605 'n' => top = advance_section(section_starts.items, cur_section, 1),606 'p' => top = advance_section(section_starts.items, cur_section, -1),607 'h' => top = 0,608 '?' => {609 showHelp();610 redraw = false;611 },612 else => redraw = false,613 }614615 if (redraw) {616 cur_section = sectionOf(section_starts.items, top);617 618 619 620 621 output.cursorUp(PAGE_ROWS + FOOTER_ROWS);622 drawBody(rendered.items, top, total, section_titles.items, cur_section);623 drawFooter(cur_section, MAN_PAGE.len, top, total);624 output.flush();625 }626 }627628 629 630 631 output.cursorUp(FRAME_ROWS);632 for (0..FRAME_ROWS) |_| {633 output.raw("\x1b[K\n");634 }635 output.cursorUp(FRAME_ROWS);636 output.flush();637}638639fn runPlain(_: std.Io, topic: []const u8) !void {640 const start_section: usize = if (topic.len == 0) 0 else blk: {641 for (MAN_PAGE, 0..) |sec, i| {642 if (std.mem.eql(u8, sec.id, topic)) break :blk i;643 }644 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });645 output.flush();646 return;647 };648649 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);650 defer arena.deinit();651 const allocator = arena.allocator();652653 var rendered = std.ArrayList([]const u8).empty;654 defer rendered.deinit(allocator);655656 var i: usize = start_section;657 while (i < MAN_PAGE.len) : (i += 1) {658 try renderSection(allocator, &rendered, MAN_PAGE[i]);659 }660 for (rendered.items) |line| output.raw(line);661 output.raw("\n");662 output.flush();663}664665const STDIN_FD = std.posix.STDIN_FILENO;666667fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void {668 var tio = try std.posix.tcgetattr(fd);669 saved.* = tio;670 671 672 673 674 675 tio.lflag.ECHO = false;676 tio.lflag.ICANON = false;677 tio.lflag.ISIG = false;678 tio.lflag.IEXTEN = false;679 tio.iflag.ICRNL = false;680 tio.iflag.IXON = false;681 tio.cc[@intFromEnum(std.posix.V.MIN)] = 1;682 tio.cc[@intFromEnum(std.posix.V.TIME)] = 0;683 try std.posix.tcsetattr(fd, .FLUSH, tio);684}685686fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void {687 std.posix.tcsetattr(fd, .FLUSH, saved) catch {};688}689690691692const AccentColor = struct {693 fg: []const u8,694 bar: []const u8,695};696697fn accentColors(a: Block.Accent) AccentColor {698 return switch (a) {699 .gold => .{ .fg = GOLD, .bar = GOLD },700 .mint => .{ .fg = MINT, .bar = MINT },701 .pink => .{ .fg = PINK, .bar = PINK },702 .lav => .{ .fg = LAV, .bar = LAV },703 };704}705706fn renderSection(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), sec: Section) !void {707 708 var idx_buf: [16]u8 = undefined;709 const idx_str = std.fmt.bufPrint(&idx_buf, "{d:0>2}", .{sectionIndexOf(sec.id) + 1}) catch "00";710711 const accent = accentColors(sec.accent);712 const divider = try std.fmt.allocPrint(allocator, "{s}── {s}{s}{s} {s}{s}{s}\n", .{713 c(TEXT_DIM),714 c(accent.fg), sec.title, c(RESET),715 c(TEXT_DIM), idx_str, c(RESET),716 });717 try out.append(allocator, divider);718719 for (sec.blocks) |block| {720 try renderBlock(allocator, out, block);721 }722723 724 try out.append(allocator, "\n");725}726727fn sectionIndexOf(id: []const u8) usize {728 for (MAN_PAGE, 0..) |sec, i| {729 if (std.mem.eql(u8, sec.id, id)) return i;730 }731 return 0;732}733734fn renderBlock(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), block: Block) !void {735 switch (block) {736 .chapter => try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s} {s}{s}\n\n", .{ c(TEXT_DIM), block.chapter, c(RESET), "" })),737 .title => {738 const accent = accentColors(block.accent);739 const padded_title = try std.fmt.allocPrint(allocator, " {s}◆{s} {s}{s}{s} ", .{ c(accent.bar), c(RESET), c(BOLD), block.title, c(RESET) });740 try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s}\n", .{ padded_title, "" }));741 if (block.badge.len > 0) {742 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) }));743 }744 },745 .badge => {}, 746 .accent => {}, 747 .para => {748 const wrapped = try wrap(allocator, block.para, COL_WIDTH);749 for (wrapped) |line| {750 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(TEXT), line, c(RESET) }));751 }752 },753 .cmd_sig => {754 const accent = accentColors(block.accent);755 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) }));756 },757 .cmd_block => {758 const wrapped = try wrap(allocator, block.cmd_block, COL_WIDTH);759 for (wrapped) |line| {760 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(MINT), line, c(RESET) }));761 }762 try out.append(allocator, "\n");763 },764 .flags_row => {765 const accent = accentColors(.gold);766 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) }));767 },768 .callout => {769 const accent = accentColors(block.callout.color);770 const wrapped = try wrap(allocator, block.callout.body, COL_WIDTH - 6);771 var first = true;772 for (wrapped) |line| {773 if (first) {774 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) }));775 first = false;776 } else {777 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) }));778 }779 }780 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└─{s}\n", .{ c(accent.bar), c(RESET) }));781 },782 .kaomoji_card => {783 const accent = accentColors(block.kaomoji_card.color);784 785 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) }));786 const desc_lines = try wrap(allocator, block.kaomoji_card.desc, COL_WIDTH - 10);787 for (desc_lines) |line| {788 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) }));789 }790 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) }));791 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└──{s}\n", .{ c(accent.bar), c(RESET) }));792 },793 .blank => try out.append(allocator, "\n"),794 }795}796797798fn wrap(allocator: std.mem.Allocator, text: []const u8, width: u16) ![]const []const u8 {799 var lines = std.ArrayList([]const u8).empty;800 errdefer lines.deinit(allocator);801802 var it = std.mem.splitScalar(u8, text, '\n');803 while (it.next()) |para| {804 if (para.len == 0) {805 try lines.append(allocator, "");806 continue;807 }808 var start: usize = 0;809 while (start < para.len) {810 var end = @min(start + @as(usize, width), para.len);811 if (end < para.len) {812 var back: usize = end;813 while (back > start and para[back - 1] != ' ') : (back -= 1) {}814 if (back > start) end = back;815 }816 try lines.append(allocator, std.mem.trim(u8, para[start..end], " \t"));817 start = end;818 while (start < para.len and para[start] == ' ') : (start += 1) {}819 }820 }821 return lines.toOwnedSlice(allocator);822}823824825826fn drawHeader() void {827 828 output.raw("\x1b[K");829 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) });830 output.raw("\x1b[K");831 output.p("{s} {s}(˶ᵔ ᵕ ᵔ˶){s} ready when you are{s}\n", .{ c(BG_HI), c(PINK), c(RESET), c(RESET) });832 output.raw("\x1b[K");833 output.p("{s}{s}{s}\n", .{ c(TEXT_DIM), "─" ** 80, c(RESET) });834}835836fn drawBody(lines: []const []const u8, top: usize, total: usize, titles: []const []const u8, cur_section: usize) void {837 _ = total;838 _ = titles;839 _ = cur_section;840 841 842 843 844 845 var i: usize = 0;846 while (i < PAGE_ROWS) : (i += 1) {847 output.raw("\x1b[K");848 const idx = top + i;849 if (idx < lines.len) {850 output.raw(lines[idx]);851 } else {852 output.raw("\n");853 }854 }855}856857fn drawFooter(cur_section: usize, total_sections: usize, top: usize, total: usize) void {858 const pct: usize = if (total == 0) 0 else (top * 100) / total;859 output.raw("\x1b[K");860 var sec_buf: [16]u8 = undefined;861 const sec_str = std.fmt.bufPrint(&sec_buf, "{d}", .{cur_section + 1}) catch "?";862 var tot_buf: [16]u8 = undefined;863 const tot_str = std.fmt.bufPrint(&tot_buf, "{d}", .{total_sections}) catch "?";864 var pct_buf: [16]u8 = undefined;865 const pct_str = std.fmt.bufPrint(&pct_buf, "{d}", .{pct}) catch "?";866 output.p("{s}{s}─── {s}{s:>2}/{s}{s} {s}{s:>3}%{s} {s}· ↑↓ scroll · n/p next/prev section · q quit{s}\n", .{867 c(TEXT_DIM), c(BG_HI),868 c(MINT), sec_str, tot_str, c(RESET),869 c(GOLD), pct_str, c(RESET),870 c(TEXT_DIM), c(RESET),871 });872}873874fn showHelp() void {875 output.cursorUp(FRAME_ROWS);876 for (0..FRAME_ROWS) |_| output.raw("\x1b[K\n");877 output.cursorUp(FRAME_ROWS);878 drawHeader();879 drawHelpBody();880 drawFooter(0, MAN_PAGE.len, 0, 1);881 output.flush();882883 884 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};885 _ = std.posix.poll(&pfd, -1) catch {};886 var buf: [8]u8 = undefined;887 _ = std.posix.read(STDIN_FD, &buf) catch {};888}889890fn drawHelpBody() void {891 const pairs = [_]struct { key: []const u8, desc: []const u8 }{892 .{ .key = "j / ↓", .desc = "scroll down one line" },893 .{ .key = "k / ↑", .desc = "scroll up one line" },894 .{ .key = "space", .desc = "page down" },895 .{ .key = "b / pgup", .desc = "page up" },896 .{ .key = "g / home", .desc = "jump to top" },897 .{ .key = "G / end", .desc = "jump to bottom" },898 .{ .key = "n / →", .desc = "next section" },899 .{ .key = "p / ←", .desc = "previous section" },900 .{ .key = "h", .desc = "back to top (table of contents)" },901 .{ .key = "?", .desc = "this help" },902 .{ .key = "q / esc", .desc = "leave the manpage" },903 };904 var i: usize = 0;905 while (i < PAGE_ROWS) : (i += 1) {906 output.raw("\x1b[K");907 if (i == 0) {908 output.p(" {s}{s}nina man · keys{s}\n\n", .{ c(BOLD), c(PINK), c(RESET) });909 } else if (i - 1 < pairs.len) {910 const p = pairs[i - 1];911 output.p(" {s}{s:<14}{s} {s}{s}{s}\n", .{ c(GOLD), p.key, c(RESET), c(TEXT), p.desc, c(RESET) });912 } else {913 output.raw("\n");914 }915 }916}