12345678910111213141516const std = @import("std");17const builtin = @import("builtin");18const output = @import("output.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 = "pin or unpin a flake input to a specific commit. `nina unpin` runs `nix flake update` on that input to release the pin." },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};488489490491const PAGE_ROWS: u16 = 22; 492const COL_WIDTH: u16 = 96; 493494495496const HEADER_ROWS: u16 = 3;497const FOOTER_ROWS: u16 = 1;498const FRAME_ROWS: u16 = HEADER_ROWS + PAGE_ROWS + FOOTER_ROWS;499500pub fn run(io: std.Io, topic: []const u8) !void {501 502 503 if (!(std.Io.File.stdout().isTty(io) catch false)) {504 return runPlain(io, topic);505 }506507 508 var saved: std.posix.termios = undefined;509 try rawModeEnable(STDIN_FD, &saved);510 defer rawModeDisable(STDIN_FD, saved);511512 const start_section: usize = if (topic.len == 0) 0 else blk: {513 for (MAN_PAGE, 0..) |sec, i| {514 if (std.mem.eql(u8, sec.id, topic)) break :blk i;515 }516 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });517 output.flush();518 return;519 };520521 522 523 524 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);525 defer arena.deinit();526 const allocator = arena.allocator();527528 var rendered = std.ArrayList([]const u8).empty;529 defer rendered.deinit(allocator);530531 532 533 var section_starts = std.ArrayList(usize).empty;534 defer section_starts.deinit(allocator);535 var section_titles = std.ArrayList([]const u8).empty;536 defer section_titles.deinit(allocator);537538 try section_starts.append(allocator, 0);539 for (MAN_PAGE) |sec| {540 try section_titles.append(allocator, sec.title);541 try renderSection(allocator, &rendered, sec);542 try section_starts.append(allocator, rendered.items.len);543 }544 const total: usize = rendered.items.len;545546 var top: usize = 0;547 var cur_section: usize = start_section;548 top = section_starts.items[start_section];549550 drawHeader();551 drawBody(rendered.items, top, total, section_titles.items, cur_section);552 drawFooter(cur_section, MAN_PAGE.len, top, total);553 output.flush();554555 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};556 while (true) {557 _ = std.posix.poll(&pfd, -1) catch break;558559 var buf: [8]u8 = undefined;560 const n = std.posix.read(STDIN_FD, &buf) catch break;561 if (n == 0) break;562563 const advance_section = struct {564 fn f(starts: []const usize, cur: usize, delta: i32) usize {565 var idx: i32 = @intCast(cur);566 idx += delta;567 if (idx < 0) idx = 0;568 if (idx >= @as(i32, @intCast(starts.len - 1))) idx = @intCast(starts.len - 2);569 return starts[@intCast(idx)];570 }571 }.f;572573 574 const sectionOf = struct {575 fn f(starts: []usize, t: usize) usize {576 var s: usize = 0;577 for (starts[1..], 1..) |start, i| {578 if (t < start) return i - 1;579 s = i;580 }581 return s;582 }583 }.f;584585 var redraw = true;586 if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {587 switch (buf[2]) {588 'A' => top = if (top > 0) top - 1 else 0, 589 'B' => top = if (top + 1 < total) top + 1 else top, 590 'C' => top = advance_section(section_starts.items, cur_section, 1), 591 'D' => top = advance_section(section_starts.items, cur_section, -1), 592 '5' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0, 593 '6' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1, 594 'H' => top = 0, 595 'F' => top = if (total > 0) total - 1 else 0, 596 else => redraw = false,597 }598 } else switch (buf[0]) {599 'q', 'Q', 0x1b => break, 600 'j' => top = if (top + 1 < total) top + 1 else top,601 'k' => top = if (top > 0) top - 1 else 0,602 ' ' => top = if (top + PAGE_ROWS < total) top + PAGE_ROWS else total - 1,603 'b' => top = if (top >= PAGE_ROWS) top - PAGE_ROWS else 0,604 'g' => top = 0,605 'G' => top = if (total > 0) total - 1 else 0,606 'n' => top = advance_section(section_starts.items, cur_section, 1),607 'p' => top = advance_section(section_starts.items, cur_section, -1),608 'h' => top = 0,609 '?' => {610 showHelp();611 redraw = false;612 },613 else => redraw = false,614 }615616 if (redraw) {617 cur_section = sectionOf(section_starts.items, top);618 619 620 621 622 output.cursorUp(PAGE_ROWS + FOOTER_ROWS);623 drawBody(rendered.items, top, total, section_titles.items, cur_section);624 drawFooter(cur_section, MAN_PAGE.len, top, total);625 output.flush();626 }627 }628629 630 631 632 output.cursorUp(FRAME_ROWS);633 for (0..FRAME_ROWS) |_| {634 output.raw("\x1b[K\n");635 }636 output.cursorUp(FRAME_ROWS);637 output.flush();638}639640fn runPlain(_: std.Io, topic: []const u8) !void {641 const start_section: usize = if (topic.len == 0) 0 else blk: {642 for (MAN_PAGE, 0..) |sec, i| {643 if (std.mem.eql(u8, sec.id, topic)) break :blk i;644 }645 output.p("{s}nina man: no such topic: {s}{s}\n", .{ c(PINK), topic, c(RESET) });646 output.flush();647 return;648 };649650 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);651 defer arena.deinit();652 const allocator = arena.allocator();653654 var rendered = std.ArrayList([]const u8).empty;655 defer rendered.deinit(allocator);656657 var i: usize = start_section;658 while (i < MAN_PAGE.len) : (i += 1) {659 try renderSection(allocator, &rendered, MAN_PAGE[i]);660 }661 for (rendered.items) |line| output.raw(line);662 output.raw("\n");663 output.flush();664}665666const STDIN_FD = std.posix.STDIN_FILENO;667668fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void {669 var tio = try std.posix.tcgetattr(fd);670 saved.* = tio;671 if (comptime builtin.os.tag == .linux) {672 tio.lflag.ECHO = false;673 tio.lflag.ICANON = false;674 tio.lflag.ISIG = false;675 tio.lflag.IEXTEN = false;676 tio.iflag.ICRNL = false;677 tio.iflag.IXON = false;678 tio.cc[@intFromEnum(std.posix.V.MIN)] = 1;679 tio.cc[@intFromEnum(std.posix.V.TIME)] = 0;680 }681 try std.posix.tcsetattr(fd, .FLUSH, tio);682}683684fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void {685 std.posix.tcsetattr(fd, .FLUSH, saved) catch {};686}687688689690const AccentColor = struct {691 fg: []const u8,692 bar: []const u8,693};694695fn accentColors(a: Block.Accent) AccentColor {696 return switch (a) {697 .gold => .{ .fg = GOLD, .bar = GOLD },698 .mint => .{ .fg = MINT, .bar = MINT },699 .pink => .{ .fg = PINK, .bar = PINK },700 .lav => .{ .fg = LAV, .bar = LAV },701 };702}703704fn renderSection(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), sec: Section) !void {705 706 var idx_buf: [16]u8 = undefined;707 const idx_str = std.fmt.bufPrint(&idx_buf, "{d:0>2}", .{sectionIndexOf(sec.id) + 1}) catch "00";708709 const accent = accentColors(sec.accent);710 const divider = try std.fmt.allocPrint(allocator, "{s}── {s}{s}{s} {s}{s}{s}\n", .{711 c(TEXT_DIM),712 c(accent.fg), sec.title, c(RESET),713 c(TEXT_DIM), idx_str, c(RESET),714 });715 try out.append(allocator, divider);716717 for (sec.blocks) |block| {718 try renderBlock(allocator, out, block);719 }720721 722 try out.append(allocator, "\n");723}724725fn sectionIndexOf(id: []const u8) usize {726 for (MAN_PAGE, 0..) |sec, i| {727 if (std.mem.eql(u8, sec.id, id)) return i;728 }729 return 0;730}731732fn renderBlock(allocator: std.mem.Allocator, out: *std.ArrayList([]const u8), block: Block) !void {733 switch (block) {734 .chapter => try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s} {s}{s}\n\n", .{ c(TEXT_DIM), block.chapter, c(RESET), "" })),735 .title => {736 const accent = accentColors(block.accent);737 const padded_title = try std.fmt.allocPrint(allocator, " {s}◆{s} {s}{s}{s} ", .{ c(accent.bar), c(RESET), c(BOLD), block.title, c(RESET) });738 try out.append(allocator, try std.fmt.allocPrint(allocator, "\n{s}{s}\n", .{ padded_title, "" }));739 if (block.badge.len > 0) {740 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) }));741 }742 },743 .badge => {}, 744 .accent => {}, 745 .para => {746 const wrapped = try wrap(allocator, block.para, COL_WIDTH);747 for (wrapped) |line| {748 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(TEXT), line, c(RESET) }));749 }750 },751 .cmd_sig => {752 const accent = accentColors(block.accent);753 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) }));754 },755 .cmd_block => {756 const wrapped = try wrap(allocator, block.cmd_block, COL_WIDTH);757 for (wrapped) |line| {758 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}{s}{s}\n", .{ c(MINT), line, c(RESET) }));759 }760 try out.append(allocator, "\n");761 },762 .flags_row => {763 const accent = accentColors(.gold);764 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) }));765 },766 .callout => {767 const accent = accentColors(block.callout.color);768 const wrapped = try wrap(allocator, block.callout.body, COL_WIDTH - 6);769 var first = true;770 for (wrapped) |line| {771 if (first) {772 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) }));773 first = false;774 } else {775 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) }));776 }777 }778 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└─{s}\n", .{ c(accent.bar), c(RESET) }));779 },780 .kaomoji_card => {781 const accent = accentColors(block.kaomoji_card.color);782 783 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) }));784 const desc_lines = try wrap(allocator, block.kaomoji_card.desc, COL_WIDTH - 10);785 for (desc_lines) |line| {786 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) }));787 }788 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) }));789 try out.append(allocator, try std.fmt.allocPrint(allocator, " {s}└──{s}\n", .{ c(accent.bar), c(RESET) }));790 },791 .blank => try out.append(allocator, "\n"),792 }793}794795796fn wrap(allocator: std.mem.Allocator, text: []const u8, width: u16) ![]const []const u8 {797 var lines = std.ArrayList([]const u8).empty;798 errdefer lines.deinit(allocator);799800 var it = std.mem.splitScalar(u8, text, '\n');801 while (it.next()) |para| {802 if (para.len == 0) {803 try lines.append(allocator, "");804 continue;805 }806 var start: usize = 0;807 while (start < para.len) {808 var end = @min(start + @as(usize, width), para.len);809 if (end < para.len) {810 var back: usize = end;811 while (back > start and para[back - 1] != ' ') : (back -= 1) {}812 if (back > start) end = back;813 }814 try lines.append(allocator, std.mem.trim(u8, para[start..end], " \t"));815 start = end;816 while (start < para.len and para[start] == ' ') : (start += 1) {}817 }818 }819 return lines.toOwnedSlice(allocator);820}821822823824fn drawHeader() void {825 826 output.raw("\x1b[K");827 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) });828 output.raw("\x1b[K");829 output.p("{s} {s}(˶ᵔ ᵕ ᵔ˶){s} ready when you are{s}\n", .{ c(BG_HI), c(PINK), c(RESET), c(RESET) });830 output.raw("\x1b[K");831 output.p("{s}{s}{s}\n", .{ c(TEXT_DIM), "─" ** 80, c(RESET) });832}833834fn drawBody(lines: []const []const u8, top: usize, total: usize, titles: []const []const u8, cur_section: usize) void {835 _ = total;836 _ = titles;837 _ = cur_section;838 839 840 841 842 843 var i: usize = 0;844 while (i < PAGE_ROWS) : (i += 1) {845 output.raw("\x1b[K");846 const idx = top + i;847 if (idx < lines.len) {848 output.raw(lines[idx]);849 } else {850 output.raw("\n");851 }852 }853}854855fn drawFooter(cur_section: usize, total_sections: usize, top: usize, total: usize) void {856 const pct: usize = if (total == 0) 0 else (top * 100) / total;857 output.raw("\x1b[K");858 var sec_buf: [16]u8 = undefined;859 const sec_str = std.fmt.bufPrint(&sec_buf, "{d}", .{cur_section + 1}) catch "?";860 var tot_buf: [16]u8 = undefined;861 const tot_str = std.fmt.bufPrint(&tot_buf, "{d}", .{total_sections}) catch "?";862 var pct_buf: [16]u8 = undefined;863 const pct_str = std.fmt.bufPrint(&pct_buf, "{d}", .{pct}) catch "?";864 output.p("{s}{s}─── {s}{s:>2}/{s}{s} {s}{s:>3}%{s} {s}· ↑↓ scroll · n/p next/prev section · q quit{s}\n", .{865 c(TEXT_DIM), c(BG_HI),866 c(MINT), sec_str, tot_str, c(RESET),867 c(GOLD), pct_str, c(RESET),868 c(TEXT_DIM), c(RESET),869 });870}871872fn showHelp() void {873 output.cursorUp(FRAME_ROWS);874 for (0..FRAME_ROWS) |_| output.raw("\x1b[K\n");875 output.cursorUp(FRAME_ROWS);876 drawHeader();877 drawHelpBody();878 drawFooter(0, MAN_PAGE.len, 0, 1);879 output.flush();880881 882 var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};883 _ = std.posix.poll(&pfd, -1) catch {};884 var buf: [8]u8 = undefined;885 _ = std.posix.read(STDIN_FD, &buf) catch {};886}887888fn drawHelpBody() void {889 const pairs = [_]struct { key: []const u8, desc: []const u8 }{890 .{ .key = "j / ↓", .desc = "scroll down one line" },891 .{ .key = "k / ↑", .desc = "scroll up one line" },892 .{ .key = "space", .desc = "page down" },893 .{ .key = "b / pgup", .desc = "page up" },894 .{ .key = "g / home", .desc = "jump to top" },895 .{ .key = "G / end", .desc = "jump to bottom" },896 .{ .key = "n / →", .desc = "next section" },897 .{ .key = "p / ←", .desc = "previous section" },898 .{ .key = "h", .desc = "back to top (table of contents)" },899 .{ .key = "?", .desc = "this help" },900 .{ .key = "q / esc", .desc = "leave the manpage" },901 };902 var i: usize = 0;903 while (i < PAGE_ROWS) : (i += 1) {904 output.raw("\x1b[K");905 if (i == 0) {906 output.p(" {s}{s}nina man · keys{s}\n\n", .{ c(BOLD), c(PINK), c(RESET) });907 } else if (i - 1 < pairs.len) {908 const p = pairs[i - 1];909 output.p(" {s}{s:<14}{s} {s}{s}{s}\n", .{ c(GOLD), p.key, c(RESET), c(TEXT), p.desc, c(RESET) });910 } else {911 output.raw("\n");912 }913 }914}