summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 01:15:28 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit2e6777e06e3f3e9d59ec847b98e0cb676d04296a (patch)
treede4f2cecfe92706ca7033527d326042f6e90e8a5
parent91360c20923c8ce30829f19bcd192bb78a4c3918 (diff)
downloadpardes-2e6777e06e3f3e9d59ec847b98e0cb676d04296a.tar.gz
pardes-2e6777e06e3f3e9d59ec847b98e0cb676d04296a.zip
main: the command line is commands that describe themselves, over the tree that does
The user: "the cli should be like a living documentation, similar to 9p and maybe even share the source code but with different sinks", rex's CLI the model. pardes [flags] [FILE] opens, starts or pages as it did; a first word naming a command is that command (a file named so is ./ps, or after --): ps, attach [NAME], kill NAME|--all, new [flags] [FILE] for sessions; do WORD [ARG] and words [GROUP] for the builtins; fs VERB [PATH] for the tree; help [CMD|WORD|PATH], completion SHELL, skill, version. One definition, several sinks. main.zig's `cmds` (an EnumArray over the Cmd enum: group, args, first-screen line, doc, examples, see-also) is both what args[1] is matched against and every command's help; `flags` (over the Flag enum: what it takes, its doc, session/open/old) is both the flag loop's parser and `help new`. The 70-line help_text and the flag enum kept apart from it are gone; every flag behaves as before, and --ps, --attach[=NAME], --kill=NAME, --kill-all, -h/--help and --version are the commands' old spellings for a release (EDITOR='pardes --wait' unchanged). What a word or a file does is the tree's to say: words, help WORD, help PATH, fs and the completions read /commands and /README over cloud9's Fsys, from the session (-s NAME, else $PARDES_9P, else the only one whose socket answers) or, with none, from a core this process makes (Pardes.create, never stepped: no shell, file or socket) and serves on one end of a socket pair to an Fsys on the other (`Here`: cloud9's engine, one thread), so both are the same client over the same tree. With no session, fs ls/stat/help/complete and a read of README, commands or ctl answer; a read of anything else, or a write, says it is a running session's and how to start one. do picks the ctl by /commands' scope (a pane's word needs $PARDES_PANE or -p N) and prints a refusal in the session's words. completion prints a bash, fish or zsh script that asks `pardes completion -- WORDS` back. skill prints src/skill.txt, the recipes and traps, which leaves the inventory to pardes help. version adds the 9P the tree speaks. The reference's "The pardes command" includes docs/typ/command-line.txt, `pardes help --all` (never a session's), which the builtins-json step (-Dplatform=tui) now writes too; a main.zig test fails when it is stale. test/process/cli.zig: five cases through the binary, with and without a session; flags' eight pass unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--build.zig15
-rw-r--r--docs/typ/command-line.txt300
-rw-r--r--docs/typ/reference.typ13
-rw-r--r--src/CHANGELOG.md16
-rw-r--r--src/main.zig1114
-rw-r--r--src/skill.txt47
-rw-r--r--test/process.zig2
-rw-r--r--test/process/cli.zig144
-rw-r--r--test/process_test.zig1
9 files changed, 1499 insertions, 153 deletions
diff --git a/build.zig b/build.zig
index 7bd43795..71c8637b 100644
--- a/build.zig
+++ b/build.zig
@@ -878,7 +878,7 @@ pub fn build(b: *std.Build) void {
// `typst compile` reads it too; a unit test fails when it is stale.
// A terminal build writes builtins-tui.json and a window build
// builtins-gui.json; style.typ merges the two into one glossary.
- const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-<tui|gui>.json from the builtin registry (-Dplatform=tui or gui)");
+ const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-<tui|gui>.json from the builtin registry, and with tui docs/typ/command-line.txt from pardes help --all (-Dplatform=tui or gui)");
if (requested_platform == .tui or requested_platform == .gui) {
const gen = b.addExecutable(.{ .name = "pardes-gen-builtins-json", .root_module = b.createModule(.{
.target = target,
@@ -1184,6 +1184,19 @@ pub fn build(b: *std.Build) void {
.root_module = root_mod,
});
installHome(b, exe, home_bin);
+ // docs/typ/command-line.txt: `pardes help --all`, the commands'
+ // help and the tree's README as this build prints them (never a
+ // session's), which the reference's "The pardes command" shows;
+ // main.zig's test fails when it is stale. The terminal's build
+ // writes it, the window's prints the same.
+ if (requested_platform == .tui) {
+ const run_help = b.addRunArtifact(exe);
+ run_help.addArgs(&.{ "help", "--all" });
+ const update = b.addUpdateSourceFiles();
+ update.addCopyFileToSource(run_help.captureStdOut(.{}), "docs/typ/command-line.txt");
+ builtins_json_step.dependOn(&update.step);
+ for (doc_renders) |r| if (r) |run| run.step.dependOn(&update.step);
+ }
// The addons, a step each: the default install is the binaries
// alone, and `zig build image pdf` (or `addons`) puts the libraries
// where the start scan finds them, <prefix>/lib/pardes/addons (and
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt
new file mode 100644
index 00000000..21b218c7
--- /dev/null
+++ b/docs/typ/command-line.txt
@@ -0,0 +1,300 @@
+pardes: an editor, a terminal multiplexer, and the file tree that scripts both.
+
+Usage:
+ pardes [flags] [FILE[:LINE] | DIR | -] open, start a session, or page stdin
+ pardes COMMAND [ARGS] [-s NAME] a file named like a command: pardes ./ps
+
+Open:
+ FILE[:LINE] open it; in a pane, in that pane's session
+ -w, --wait FILE open it, return when its pane closes (EDITOR='pardes -w')
+ - stdin into a +Pager, its colours kept
+ DIR start in it
+
+Sessions:
+ ps the daemon's sessions, their clients and shells
+ attach [NAME] show a detached session here (HOST:NAME: over ssh)
+ kill NAME end a session and its shells (--all: every one)
+ new [flags] [FILE] start one: --detach=NAME --9p=NAME -n 3 (help new)
+
+Words:
+ do WORD [ARG] run a builtin at this pane, or the session's: do Newcol
+ words [GROUP] the builtins by group, or one group's: words column
+
+Files:
+ fs VERB [PATH] ls read write ask follow stat help complete, on the session's tree
+
+Self:
+ help [CMD|WORD|PATH] this, a command, a builtin, or a file of the tree
+ completion SHELL bash, fish or zsh
+ skill the guide an agent reads
+ version this build, its session wire and its 9P
+
+Flags:
+ -s, --session NAME the session to act on ($PARDES_9P, else the only one)
+ -p N the pane, for do ($PARDES_PANE)
+
+The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and
+--version still work, for a release.
+
+== pardes help ps
+
+What the per-user daemon keeps: each session with its name, pid, kind
+(tty or gui) and whether one is attached; under it its clients and its
+shells; then the shells no session holds, which Adopt takes. /sessions
+is the same list, read from inside a session.
+
+Usage:
+ pardes ps
+
+Examples:
+ pardes ps every session, client and shell
+
+See also: attach, kill, /sessions
+
+== pardes help attach
+
+Show a detached session here: in this terminal for pardes, a window
+for pardes-gui. Bare, the one detached session (with none, the one
+session). One attached already, or of the other kind, is joined as a
+client. HOST:NAME is a client of session NAME on another machine,
+over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh
+command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory,
+if not this one's path); SOCK:NAME goes through a socket forwarded
+already (a path, with a '/'). Returns when the session detaches or
+ends.
+
+Usage:
+ pardes attach [NAME]
+
+Examples:
+ pardes attach the one detached session
+ pardes attach notes the one started with --detach=notes
+ pardes attach box:notes on host box, over ssh -L
+ pardes attach /run/x.sock:notes through a socket forwarded already
+
+See also: ps, kill, new --detach, the Detach word
+
+== pardes help kill
+
+End session NAME (its --9p or --detach name, else its pid) and its
+shells: TERM, then KILL 2 s later. Unsaved changes are lost. --all
+ends every session and every shell the daemon keeps.
+
+Usage:
+ pardes kill NAME
+
+Examples:
+ pardes kill notes the session started with --detach=notes
+ pardes kill --all every session and shell
+
+See also: ps, attach
+
+== pardes help new
+
+Start a session here, even in a pane of another: in this terminal for
+pardes, a window for pardes-gui, or with --detach none until one
+attaches. Bare `pardes` takes the same flags, and starts one unless
+it is in a pane (where it hands its FILE to that session).
+
+Usage:
+ pardes new [flags] [FILE]
+
+Flags:
+ --tty start as one shell pane already in tty mode
+ -n COUNT shell panes to start with: 1 (default) or 3 (classic); a FILE boots just that file
+ --tty-toggle KEY Ctrl-KEY toggles tty and editor mode
+ -l DUMP load a dump of another instance (see Dump)
+ --nested a session of its own in a pane of another, serving none of its children
+ --9p=NAME name the 9P socket (else the --detach name, else the pid); under $XDG_RUNTIME_DIR, else ~/.local/state/pardes: a directory of yours alone
+ --9p-tcp=tcp!IP!PORT also serve 9P there, a numeric address
+ --mount=NAME=DIAL a 9P session or Unix/TCP endpoint under /n/NAME; repeat for more; os and self are reserved
+ --geometry=WxH[+X+Y] the window's size in points, and where it goes where the display lets a window say (X11)
+ --detach[=NAME] no terminal (no window) until one attaches; panes, shells and files stay; NAME (one path component) rather than the pid. One pardes --daemon per user keeps sessions (PARDES_DAEMON=off: none)
+ -w, --wait in a pane, hand FILE to its session and return once its pane is deleted: 0, or 1 if the session goes (EDITOR='pardes --wait')
+ -- the end of the flags: pardes -- -name opens -name
+
+Examples:
+ pardes new a session here, its shell pane in tty mode
+ pardes new --detach=notes one with no terminal, named notes
+ pardes new -n 3 src/ three shell panes in src/
+ pardes new --mount=peer=notes with session notes under /n/peer
+
+See also: attach, kill, --nested
+
+== pardes help do
+
+Write WORD and its ARG to the ctl that takes it, as the session's
+/commands says: the root's /ctl for a session's word, a pane's
+pane/N/ctl for a pane's, that pane being this shell's ($PARDES_PANE)
+or -p N. A refusal prints the session's own words, and the exit is 1.
+The session is -s NAME, else $PARDES_9P, else the only one running.
+
+Usage:
+ pardes do WORD [ARG]
+
+Examples:
+ pardes do Newcol an empty column
+ pardes do Save -p 3 save pane 3
+ pardes do Edit ',x/foo/c/bar/' -p 3 sam's Edit on pane 3
+ pardes do Wrap -s notes at session notes
+
+See also: words, help WORD, /commands
+
+== pardes help words
+
+The session's builtins, as its /commands lists them, grouped by the
+first key after the leader (SPC f is file, SPC c column): with no key,
+a setting, a session's word (its root ctl's) or a text word (a
+pane's). An addon's words are the addon group. With no session, the
+ones this build has.
+
+Usage:
+ pardes words [GROUP]
+
+Examples:
+ pardes words every builtin, by group
+ pardes words column the column words
+
+See also: do, help WORD, /commands
+
+== pardes help fs
+
+The session's file tree, through a 9P client in this binary: the
+files a mount or 9p(1) reaches, with a refusal in the session's own
+words (a mount says only EINVAL). With no session, ls, stat, help and
+complete, and a read of README, commands or ctl, ask a core made in
+this process; the rest are a running session's, and say so.
+
+Usage:
+ pardes fs VERB [PATH]
+
+usage: fs ls [PATH] the names in a directory, a / after each directory
+ fs read PATH the file, to its end (a held read streams)
+ fs write PATH [WORDS...] the words and a newline, else stdin, as > would
+ fs ask PATH WORDS... write the words and read the answer on the same open
+ fs follow PATH [WORDS...] ask, or read: what comes, as it comes, for as long
+ fs stat PATH mode length uid gid mtime name
+ fs help [PATH] what the tree's README says of PATH
+ fs complete [PREFIX] the paths that go on from PREFIX, for a shell
+
+Examples:
+ pardes fs ls pane/1 what a pane serves
+ pardes fs read index a line per pane
+ pardes fs write pane/3/ctl 'Edit ,x/foo/c/bar/' a write, refused in words
+ pardes fs ask pane/3/pty/run make exit N, then the output
+ pardes fs follow log follow events as they come
+
+See also: help PATH, /README
+
+== pardes help help
+
+Bare, this map. A command: what it does, with examples. A builtin:
+its /commands line, its key, and how to run it. A path of the tree:
+what the tree's README says of it and of what is under it. --all:
+every command's help and the README whole, as this build has them
+(never a session's), which the reference prints.
+
+Usage:
+ pardes help [CMD|WORD|PATH]
+
+Examples:
+ pardes help attach a command
+ pardes help Newcol a builtin
+ pardes help pane/3/addr a file of the tree
+
+See also: words, fs help
+
+== pardes help completion
+
+A completion script for SHELL, printed, never installed. It asks this
+binary back for each word (`pardes completion -- WORDS`): commands,
+the builtins after do, sessions after attach and kill, the tree's
+paths after fs.
+
+Usage:
+ pardes completion SHELL
+
+Examples:
+ pardes completion fish | source in fish, for this shell
+ source <(pardes completion bash) in bash
+ source <(pardes completion zsh) in zsh
+
+== pardes help skill
+
+The guide for an agent that drives pardes, from this binary, so it
+matches what it runs: recipes and traps. What is there it leaves to
+`pardes help`.
+
+Usage:
+ pardes skill
+
+Examples:
+ pardes skill
+
+== pardes help version
+
+This build's version; the semantics a replica must share with its
+session; the 9P its tree speaks.
+
+Usage:
+ pardes version
+
+Examples:
+ pardes version
+
+== the old spellings
+
+ --attach[=NAME] pardes attach NAME
+ --ps pardes ps
+ --kill=NAME pardes kill NAME
+ --kill-all pardes kill --all
+ -h, --help pardes help
+ --version pardes version
+
+== pardes help /: the tree's README
+
+Pardes virtual filesystem
+=========================
+README this summary; the pardes book's Scripting and Reference chapters have the rest
+index a line per pane: serial kind(text|term|cmd|pdf|image|an addon's) dirty name column; names hold blanks: rsplit(maxsplit=1)
+status pid, version and pane count
+look write a line: a right click on it at the pane with the keyboard; read: the serials it touched (this open's)
+exec write a line: a middle click, a builtin or a shell line; read the same (every exec file)
+pager write a directory: its one +Pager, made or emptied; read the same open: its serial (pardes -)
+log events: new del rename save newcol delcol run exit send ask answer changed dump restore restored restoredcol msg err
+screen the rendered screen as JSON, frozen from open to close
+listeners the session's dial addresses
+sessions the pardes daemon's, as pardes --ps: daemon <pid>; session <pid> tty|gui attached|detached <name>; shell <pid>; orphan <pid>
+focus the serial of the pane with the keyboard (empty on a column tag); write one to give it the keyboard
+kbdin write runes: keys typed at the pane with the keyboard, done before the write answers (\x1b Esc, \n Enter)
+mousein write `m col row buttons` (1 left, 2 middle, 4 right): the mouse as it now is; m 10 5 4, m 10 5 0 is a right click
+ctl settings a line; or Newcol, Dump [export f], Restore [label|f], Exit (refuses once over unsaved panes), Kill [w], size C R
+commands every builtin: word, arg, root|pane|both (the ctl that takes it), -- what it does; addons: the kinds of pane here
+recent files opened lately, closed ones too: open|closed <path>
+dumps the dumps the state file keeps, the newest first: <label> <date> <size> <panes>
+layout a line per column: serial index x width current|notcurrent empty|full pane-serials; then active <serial>
+tag the workspace tag, tagexec a word as a click in it; col/<serial>/ a column's tag, ctl, exec; rmdir: empty only
+pane/new open it to make a pane (<session dir>/+New) in the active column; the read answers its serial
+pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec; rmdir closes
+ on terminals pty/data (keys in, output out), pty/status, pty/ctl (winsize, sig, exec), pty/run (a line, its exit and output)
+os/ the host filesystem
+
+$m below: $PARDES_MOUNT (set under 9ns --mntgen); without it, 9p -a "unix!$PARDES_9P".
+
+ cat $m/index which panes exist
+ n=$(cat $m/pane/new) make a pane of your own (each open makes one), take its serial
+ exec 3<>$m/pane/$n/look; echo /etc/hosts:3 >&3; cat <&3 open a file through it, see the pane it went to
+ printf 'text\n' >> $m/pane/$n/body append to it (> replaces it all)
+ echo 'Msg hello' > $m/pane/$n/exec show text in the editor
+ echo 'Edit ,x/foo/c/bar/' > $m/pane/$n/ctl sam's Edit, one undo step; an x that matches nothing succeeds
+ echo /re/ > $m/pane/$n/addr; printf new > $m/pane/$n/data replace the next match
+ exec 3<>$m/log; echo follow >&3; cat <&3 what happened lately, then wait for more
+ exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 exit N, then the output
+
+Traps:
+ A refused write says only EINVAL or EIO; grep '^err' log | tail -1 says why (not the last line, maybe +Unsaved's new).
+ Root look and exec act at the pane with the keyboard, which another client may own: use a pane's own look and exec.
+ addr is the pane's and moves on: each /re/ searches from the last, a data write leaves it past the text.
+ Through a mount, printf 'a\nb\n' arrives a line a write: send a block with one write, ending in a newline.
+ Pane words (Save Undo Del) go to pane/<n>/ctl, settings and session words to /ctl.
+ Exit, Restore, Del and get refuse once over unsaved text; the same word again discards.
diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ
index 7360179f..d359489b 100644
--- a/docs/typ/reference.typ
+++ b/docs/typ/reference.typ
@@ -1172,6 +1172,19 @@ says the session is gone); with
waits there. Bare `pardes` in a pane refuses and names `--nested`, which
starts a separate session whose shells do not forward to it.
+A first word that names a command is that command instead (a file named
+so is `./ps`, or after `--`): `ps`, `attach`, `kill` and `new` for
+sessions; `do WORD` and `words` for the builtins of #file("/commands");
+`fs` for the tree, through a 9P client in the binary, a refusal in the
+session's own words; `help`, `completion`, `skill` and `version`. A
+command that acts on a session takes `-s NAME`, else `$PARDES_9P`, else
+the only one running; with none, `help`, `words`, `completion` and a read
+of #file("/README"), #file("/commands") or #file("/ctl") ask a core made
+in the command's own process. What follows is `pardes help --all`, printed
+by the build (docs/typ/command-line.txt), so it is what the binary says.
+
+#raw(read("command-line.txt"), block: true)
+
= Placement <placement>
A new pane goes in the column whose tag asked, else the active column (last typed or left-clicked in,
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md
index da489b82..17bd01a5 100644
--- a/src/CHANGELOG.md
+++ b/src/CHANGELOG.md
@@ -2,6 +2,22 @@
## Unreleased
+- `pardes` has commands, and they describe themselves: `ps`, `attach`,
+ `kill` and `new` for sessions, `do WORD` and `words` for the builtins,
+ `fs ls|read|write|ask|follow|stat|help|complete PATH` for the tree (a
+ refusal in the session's own words, where a mount says EINVAL), and
+ `help`, `completion bash|fish|zsh`, `skill` and `version`. `pardes help`
+ is a map of them; `help CMD` ends in examples; `help WORD` and `help
+ PATH` print what the session's /commands and /README say, and with no
+ session running, what a core made in the command's own process says.
+ A command acts on `-s NAME`, else `$PARDES_9P`, else the only session.
+ `pardes FILE` and every flag work as before; `--ps`, `--attach`,
+ `--kill`, `--kill-all`, `--help` and `--version` are the commands' old
+ spellings, for a release. A file named like a command opens as `./ps`.
+ The reference's "The pardes command" is `pardes help --all`, written by
+ `zig build builtins-json -Dplatform=tui`, and a test says when it is
+ stale.
+
- A drag draws no guide lines: no dashes where a pane or column would
land, no rail for a carried column, no dashed seam under a pane rule
held. The line between two columns no longer resizes them (nor, at a
diff --git a/src/main.zig b/src/main.zig
index ed20dceb..1c4ab852 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -4,6 +4,7 @@ const pardes = @import("pardes.zig");
const ninep_io = @import("9p_io.zig");
const daemon = @import("daemon.zig");
const upgrade = @import("upgrade.zig");
+const cloud9 = @import("cloud9");
pub const std_options_debug_threaded_io: ?*std.Io.Threaded = std.Io.Threaded.global_single_threaded;
pub const std_options_debug_io: std.Io = std_options_debug_threaded_io.?.io();
@@ -55,81 +56,6 @@ pub const debug = struct {
}
};
-const help_text =
- \\Usage: pardes [options] [file|dir|-]
- \\
- \\With no arguments the shell pane starts in tty mode. A FILE argument
- \\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY
- \\argument becomes the cwd shells spawn in. `-` reads stdin into a +Pager
- \\pane, its colours kept and every other escape dropped:
- \\inside a pardes pane the outer session's, returning at once (a
- \\terminal's PAGER), else a new editor's.
- \\
- \\Options:
- \\ --tty start as one shell pane already in tty mode
- \\ -n <count> initial shell panes: 1 (default) or 3 (classic).
- \\ A FILE argument boots just that file instead.
- \\ --tty-toggle <key> use Ctrl-<key> to toggle tty/editor mode
- \\ -l <dump> load a dump of another instance (see Dump)
- \\ -w, --wait inside a pardes pane, hand FILE to the outer
- \\ session and return only once the pane it opened
- \\ (or already had) is deleted: 0 then, 1 if the
- \\ session goes away. For $EDITOR (acme's E):
- \\ EDITOR='pardes --wait', which GIT_EDITOR follows.
- \\ Outside pardes a session blocks anyway.
- \\ --nested run a full session even inside another pardes.
- \\ Without it, a pardes started inside a pardes
- \\ hands its FILE argument to the outer one. This
- \\ session will not serve its own children either.
- \\ Explicit session configuration starts a new one.
- \\ --9p=<name> name the default 9P socket. Without this flag,
- \\ the name is the detached session name or pid.
- \\ The socket is under $XDG_RUNTIME_DIR, falling
- \\ back to ~/.local/state/pardes: a directory
- \\ of the user's alone (mode 700), or none.
- \\ --9p-tcp=<dial> also serve 9P at tcp!<numeric-ip>!<port>.
- \\ --mount=<name>=<dial> mount a 9P session or Unix/TCP endpoint under /n/<name>.
- \\ Repeat for more mounts; os and self are reserved.
- \\ --detach run this session with no terminal (no window)
- \\ until one attaches; its panes, shells and files
- \\ stay. Detach, or a terminal that closes, leaves
- \\ any session so. One `pardes --daemon` per user
- \\ keeps them (PARDES_DAEMON=off: none)
- \\ --detach=<name> ...named <name> rather than this process's pid,
- \\ as --9p names it. One path component: no '/'
- \\ and nothing empty
- \\ --attach show the one detached session here (with
- \\ none, the one session): in this terminal for
- \\ `pardes`, a window for `pardes-gui`. One
- \\ attached already, or of the other kind (a
- \\ window's session in a terminal, or the
- \\ reverse), is joined as a client, as
- \\ --attach=<sock>:<name>. Returns when the
- \\ session detaches or ends
- \\ --attach=<name> ...the session called <name> (its --9p or
- \\ --detach name, else its pid; see --ps)
- \\ --attach=<host>:<name> a client of session <name> on another machine,
- \\ a terminal's or a window's (either kind's
- \\ session), over `ssh -L` to its pardes-replica.sock
- \\ ($PARDES_SSH: the ssh command, words, default
- \\ `ssh`; and
- \\ $PARDES_REMOTE_RUNTIME: its runtime directory,
- \\ if not this one's path). Its keys show at once
- \\ --attach=<sock>:<name> ...through that socket (a path, with a '/'),
- \\ one forwarded already, or this machine's
- \\ --ps what the pardes daemon keeps: each session (its
- \\ pid, kind, whether attached), its clients and its
- \\ shells, then the shells no session holds
- \\ --kill=<name> end session <name> and its shells (TERM, then
- \\ KILL 2 s later); unsaved changes are lost
- \\ --kill-all end every session and every shell the daemon keeps
- \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes
- \\ where the display lets a window say (X11)
- \\ -h, --help show this help and exit
- \\ --version print the version and exit
- \\
-;
-
/// `pardes -` inside a session: `text`, stdin as it came, escapes and all,
/// into a new +Pager of the directory (/pager):
/// written after the directory on that one open, the session parses it
@@ -287,7 +213,7 @@ fn hasPane(index: []const u8, serial: u32) bool {
}
fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
- die(io, fmt ++ "\nTry 'pardes --help'.", args);
+ die(io, fmt ++ "\nTry 'pardes help', or 'pardes help new' for the flags.", args);
}
/// `pardes: <words>` on stderr, and exit 1.
@@ -309,6 +235,831 @@ const nested_text =
\\
;
+// ---- the command line ----
+//
+// `pardes [flags] [FILE]` opens, starts or pages, as it always has; a first
+// word that names a `Cmd` is that command instead (a file called so is
+// `./ps`, or after `--`). `cmds` and `flags` are each both the parser and the
+// help: `pardes help` prints them, and `pardes help --all` prints them whole
+// with the tree's README, which is docs/typ/command-line.txt (the build's
+// builtins-json step writes it; a test below says when it is stale). What a
+// word or a file does is the tree's to say: `words`, `help WORD`, `help
+// PATH`, `fs` and the completions read /commands and /README, from the
+// session over 9P or, with none, from a core made in this process (`Here`).
+
+const Cmd = enum { ps, attach, kill, new, do, words, fs, help, completion, skill, version };
+
+const Group = enum { Sessions, Words, Files, Self };
+
+const Doc = struct {
+ group: Group,
+ args: []const u8 = "",
+ /// Its line on the first screen.
+ line: []const u8,
+ /// `pardes help CMD`: what it does.
+ doc: []const u8,
+ /// A command line and what it does, each.
+ examples: []const [2][]const u8,
+ see: []const u8 = "",
+};
+
+const cmds = std.EnumArray(Cmd, Doc).init(.{
+ .ps = .{
+ .group = .Sessions,
+ .line = "the daemon's sessions, their clients and shells",
+ .doc =
+ \\What the per-user daemon keeps: each session with its name, pid, kind
+ \\(tty or gui) and whether one is attached; under it its clients and its
+ \\shells; then the shells no session holds, which Adopt takes. /sessions
+ \\is the same list, read from inside a session.
+ ,
+ .examples = &.{.{ "pardes ps", "every session, client and shell" }},
+ .see = "attach, kill, /sessions",
+ },
+ .attach = .{
+ .group = .Sessions,
+ .args = "[NAME]",
+ .line = "show a detached session here (HOST:NAME: over ssh)",
+ .doc =
+ \\Show a detached session here: in this terminal for pardes, a window
+ \\for pardes-gui. Bare, the one detached session (with none, the one
+ \\session). One attached already, or of the other kind, is joined as a
+ \\client. HOST:NAME is a client of session NAME on another machine,
+ \\over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh
+ \\command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory,
+ \\if not this one's path); SOCK:NAME goes through a socket forwarded
+ \\already (a path, with a '/'). Returns when the session detaches or
+ \\ends.
+ ,
+ .examples = &.{
+ .{ "pardes attach", "the one detached session" },
+ .{ "pardes attach notes", "the one started with --detach=notes" },
+ .{ "pardes attach box:notes", "on host box, over ssh -L" },
+ .{ "pardes attach /run/x.sock:notes", "through a socket forwarded already" },
+ },
+ .see = "ps, kill, new --detach, the Detach word",
+ },
+ .kill = .{
+ .group = .Sessions,
+ .args = "NAME",
+ .line = "end a session and its shells (--all: every one)",
+ .doc =
+ \\End session NAME (its --9p or --detach name, else its pid) and its
+ \\shells: TERM, then KILL 2 s later. Unsaved changes are lost. --all
+ \\ends every session and every shell the daemon keeps.
+ ,
+ .examples = &.{
+ .{ "pardes kill notes", "the session started with --detach=notes" },
+ .{ "pardes kill --all", "every session and shell" },
+ },
+ .see = "ps, attach",
+ },
+ .new = .{
+ .group = .Sessions,
+ .args = "[flags] [FILE]",
+ .line = "start one: --detach=NAME --9p=NAME -n 3 (help new)",
+ .doc =
+ \\Start a session here, even in a pane of another: in this terminal for
+ \\pardes, a window for pardes-gui, or with --detach none until one
+ \\attaches. Bare `pardes` takes the same flags, and starts one unless
+ \\it is in a pane (where it hands its FILE to that session).
+ ,
+ .examples = &.{
+ .{ "pardes new", "a session here, its shell pane in tty mode" },
+ .{ "pardes new --detach=notes", "one with no terminal, named notes" },
+ .{ "pardes new -n 3 src/", "three shell panes in src/" },
+ .{ "pardes new --mount=peer=notes", "with session notes under /n/peer" },
+ },
+ .see = "attach, kill, --nested",
+ },
+ .do = .{
+ .group = .Words,
+ .args = "WORD [ARG]",
+ .line = "run a builtin at this pane, or the session's: do Newcol",
+ .doc =
+ \\Write WORD and its ARG to the ctl that takes it, as the session's
+ \\/commands says: the root's /ctl for a session's word, a pane's
+ \\pane/N/ctl for a pane's, that pane being this shell's ($PARDES_PANE)
+ \\or -p N. A refusal prints the session's own words, and the exit is 1.
+ \\The session is -s NAME, else $PARDES_9P, else the only one running.
+ ,
+ .examples = &.{
+ .{ "pardes do Newcol", "an empty column" },
+ .{ "pardes do Save -p 3", "save pane 3" },
+ .{ "pardes do Edit ',x/foo/c/bar/' -p 3", "sam's Edit on pane 3" },
+ .{ "pardes do Wrap -s notes", "at session notes" },
+ },
+ .see = "words, help WORD, /commands",
+ },
+ .words = .{
+ .group = .Words,
+ .args = "[GROUP]",
+ .line = "the builtins by group, or one group's: words column",
+ .doc =
+ \\The session's builtins, as its /commands lists them, grouped by the
+ \\first key after the leader (SPC f is file, SPC c column): with no key,
+ \\a setting, a session's word (its root ctl's) or a text word (a
+ \\pane's). An addon's words are the addon group. With no session, the
+ \\ones this build has.
+ ,
+ .examples = &.{
+ .{ "pardes words", "every builtin, by group" },
+ .{ "pardes words column", "the column words" },
+ },
+ .see = "do, help WORD, /commands",
+ },
+ .fs = .{
+ .group = .Files,
+ .args = "VERB [PATH]",
+ .line = "ls read write ask follow stat help complete, on the session's tree",
+ .doc =
+ \\The session's file tree, through a 9P client in this binary: the
+ \\files a mount or 9p(1) reaches, with a refusal in the session's own
+ \\words (a mount says only EINVAL). With no session, ls, stat, help and
+ \\complete, and a read of README, commands or ctl, ask a core made in
+ \\this process; the rest are a running session's, and say so.
+ ,
+ .examples = &.{
+ .{ "pardes fs ls pane/1", "what a pane serves" },
+ .{ "pardes fs read index", "a line per pane" },
+ .{ "pardes fs write pane/3/ctl 'Edit ,x/foo/c/bar/'", "a write, refused in words" },
+ .{ "pardes fs ask pane/3/pty/run make", "exit N, then the output" },
+ .{ "pardes fs follow log follow", "events as they come" },
+ },
+ .see = "help PATH, /README",
+ },
+ .help = .{
+ .group = .Self,
+ .args = "[CMD|WORD|PATH]",
+ .line = "this, a command, a builtin, or a file of the tree",
+ .doc =
+ \\Bare, this map. A command: what it does, with examples. A builtin:
+ \\its /commands line, its key, and how to run it. A path of the tree:
+ \\what the tree's README says of it and of what is under it. --all:
+ \\every command's help and the README whole, as this build has them
+ \\(never a session's), which the reference prints.
+ ,
+ .examples = &.{
+ .{ "pardes help attach", "a command" },
+ .{ "pardes help Newcol", "a builtin" },
+ .{ "pardes help pane/3/addr", "a file of the tree" },
+ },
+ .see = "words, fs help",
+ },
+ .completion = .{
+ .group = .Self,
+ .args = "SHELL",
+ .line = "bash, fish or zsh",
+ .doc =
+ \\A completion script for SHELL, printed, never installed. It asks this
+ \\binary back for each word (`pardes completion -- WORDS`): commands,
+ \\the builtins after do, sessions after attach and kill, the tree's
+ \\paths after fs.
+ ,
+ .examples = &.{
+ .{ "pardes completion fish | source", "in fish, for this shell" },
+ .{ "source <(pardes completion bash)", "in bash" },
+ .{ "source <(pardes completion zsh)", "in zsh" },
+ },
+ },
+ .skill = .{
+ .group = .Self,
+ .line = "the guide an agent reads",
+ .doc =
+ \\The guide for an agent that drives pardes, from this binary, so it
+ \\matches what it runs: recipes and traps. What is there it leaves to
+ \\`pardes help`.
+ ,
+ .examples = &.{.{ "pardes skill", "" }},
+ },
+ .version = .{
+ .group = .Self,
+ .line = "this build, its session wire and its 9P",
+ .doc =
+ \\This build's version; the semantics a replica must share with its
+ \\session; the 9P its tree speaks.
+ ,
+ .examples = &.{.{ "pardes version", "" }},
+ },
+});
+
+/// The flags of `pardes [flags] [FILE]` and `pardes new`, and the spellings
+/// the commands had before (one release more).
+const Flag = enum { @"--tty", @"-n", @"--tty-toggle", @"-l", @"--nested", @"--9p", @"--9p-tcp", @"--mount", @"--geometry", @"--detach", @"-w", @"--wait", @"--", @"--attach", @"--ps", @"--kill", @"--kill-all", @"-h", @"--help", @"--version" };
+
+const FlagDoc = struct {
+ /// What follows it: ` COUNT` (the next argument, or after `=`), `=NAME`
+ /// (after `=` only), `[=NAME]` (maybe).
+ arg: []const u8 = "",
+ takes: enum { none, next, eq, maybe } = .none,
+ /// Empty: a short spelling of the flag after it, printed with it.
+ doc: []const u8 = "",
+ group: enum { session, open, old } = .session,
+};
+
+const flags = std.EnumArray(Flag, FlagDoc).init(.{
+ .@"--tty" = .{ .doc = "start as one shell pane already in tty mode" },
+ .@"-n" = .{ .arg = " COUNT", .takes = .next, .doc = "shell panes to start with: 1 (default) or 3 (classic); a FILE boots just that file" },
+ .@"--tty-toggle" = .{ .arg = " KEY", .takes = .next, .doc = "Ctrl-KEY toggles tty and editor mode" },
+ .@"-l" = .{ .arg = " DUMP", .takes = .next, .doc = "load a dump of another instance (see Dump)" },
+ .@"--nested" = .{ .doc = "a session of its own in a pane of another, serving none of its children" },
+ .@"--9p" = .{ .arg = "=NAME", .takes = .eq, .doc = "name the 9P socket (else the --detach name, else the pid); under $XDG_RUNTIME_DIR, else ~/.local/state/pardes: a directory of yours alone" },
+ .@"--9p-tcp" = .{ .arg = "=tcp!IP!PORT", .takes = .eq, .doc = "also serve 9P there, a numeric address" },
+ .@"--mount" = .{ .arg = "=NAME=DIAL", .takes = .eq, .doc = "a 9P session or Unix/TCP endpoint under /n/NAME; repeat for more; os and self are reserved" },
+ .@"--geometry" = .{ .arg = "=WxH[+X+Y]", .takes = .eq, .doc = "the window's size in points, and where it goes where the display lets a window say (X11)" },
+ .@"--detach" = .{ .arg = "[=NAME]", .takes = .maybe, .doc = "no terminal (no window) until one attaches; panes, shells and files stay; NAME (one path component) rather than the pid. One pardes --daemon per user keeps sessions (PARDES_DAEMON=off: none)" },
+ .@"-w" = .{ .group = .open },
+ .@"--wait" = .{ .group = .open, .doc = "in a pane, hand FILE to its session and return once its pane is deleted: 0, or 1 if the session goes (EDITOR='pardes --wait')" },
+ .@"--" = .{ .group = .open, .doc = "the end of the flags: pardes -- -name opens -name" },
+ .@"--attach" = .{ .arg = "[=NAME]", .takes = .maybe, .group = .old, .doc = "pardes attach NAME" },
+ .@"--ps" = .{ .group = .old, .doc = "pardes ps" },
+ .@"--kill" = .{ .arg = "=NAME", .takes = .eq, .group = .old, .doc = "pardes kill NAME" },
+ .@"--kill-all" = .{ .group = .old, .doc = "pardes kill --all" },
+ .@"-h" = .{ .group = .old },
+ .@"--help" = .{ .group = .old, .doc = "pardes help" },
+ .@"--version" = .{ .group = .old, .doc = "pardes version" },
+});
+
+const first_screen_head =
+ \\pardes: an editor, a terminal multiplexer, and the file tree that scripts both.
+ \\
+ \\Usage:
+ \\ pardes [flags] [FILE[:LINE] | DIR | -] open, start a session, or page stdin
+ \\ pardes COMMAND [ARGS] [-s NAME] a file named like a command: pardes ./ps
+ \\
+ \\Open:
+ \\ FILE[:LINE] open it; in a pane, in that pane's session
+ \\ -w, --wait FILE open it, return when its pane closes (EDITOR='pardes -w')
+ \\ - stdin into a +Pager, its colours kept
+ \\ DIR start in it
+ \\
+;
+
+const first_screen_tail =
+ \\
+ \\Flags:
+ \\ -s, --session NAME the session to act on ($PARDES_9P, else the only one)
+ \\ -p N the pane, for do ($PARDES_PANE)
+ \\
+ \\The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and
+ \\--version still work, for a release.
+ \\
+;
+
+/// The left column of the first screen and the flag lists.
+const left_width = 23;
+
+fn writeFirstScreen(w: *std.Io.Writer) std.Io.Writer.Error!void {
+ try w.writeAll(first_screen_head);
+ for (std.enums.values(Group)) |g| {
+ try w.print("\n{t}:\n", .{g});
+ for (std.enums.values(Cmd)) |c| {
+ const d = cmds.get(c);
+ if (d.group != g) continue;
+ var buf: [64]u8 = undefined;
+ const left = std.fmt.bufPrint(&buf, "{t}{s}{s}", .{ c, if (d.args.len == 0) "" else " ", d.args }) catch unreachable; // the table's names fit
+ try w.print(" {s}", .{left});
+ try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2);
+ try w.print("{s}\n", .{d.line});
+ }
+ }
+ try w.writeAll(first_screen_tail);
+}
+
+fn writeFlags(w: *std.Io.Writer, group: @FieldType(FlagDoc, "group")) std.Io.Writer.Error!void {
+ var short: ?Flag = null;
+ for (std.enums.values(Flag)) |f| {
+ const d = flags.get(f);
+ if (d.group != group) continue;
+ if (d.doc.len == 0) {
+ short = f;
+ continue;
+ }
+ var buf: [64]u8 = undefined;
+ const left = if (short) |s|
+ std.fmt.bufPrint(&buf, "{t}, {t}{s}", .{ s, f, d.arg }) catch unreachable // the table's names fit
+ else
+ std.fmt.bufPrint(&buf, "{t}{s}", .{ f, d.arg }) catch unreachable; // the table's names fit
+ short = null;
+ try w.print(" {s}", .{left});
+ try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2);
+ try w.print("{s}\n", .{d.doc});
+ }
+}
+
+fn writeLeaf(w: *std.Io.Writer, c: Cmd) std.Io.Writer.Error!void {
+ const d = cmds.get(c);
+ try w.print("{s}\n\nUsage:\n pardes {t}{s}{s}\n", .{ d.doc, c, if (d.args.len == 0) "" else " ", d.args });
+ switch (c) {
+ .new => {
+ try w.writeAll("\nFlags:\n");
+ try writeFlags(w, .session);
+ try writeFlags(w, .open);
+ },
+ .fs => try w.print("\n{s}", .{cloud9.verbs.usage}),
+ else => {},
+ }
+ try w.writeAll("\nExamples:\n");
+ for (d.examples) |e| {
+ try w.print(" {s}", .{e[0]});
+ if (e[1].len != 0) {
+ try w.splatByteAll(' ', if (e[0].len < 37) 38 - e[0].len else 2);
+ try w.writeAll(e[1]);
+ }
+ try w.writeByte('\n');
+ }
+ if (d.see.len != 0) try w.print("\nSee also: {s}\n", .{d.see});
+}
+
+/// Everything: the first screen, every command's help, the old spellings
+/// and the tree's README, as this build has them.
+fn writeHelpAll(w: *std.Io.Writer, t: *Tree) !void {
+ try writeFirstScreen(w);
+ for (std.enums.values(Cmd)) |c| {
+ try w.print("\n== pardes help {t}\n\n", .{c});
+ try writeLeaf(w, c);
+ }
+ try w.writeAll("\n== the old spellings\n\n");
+ try writeFlags(w, .old);
+ try w.writeAll("\n== pardes help /: the tree's README\n\n");
+ try t.f.readFile("README", w);
+}
+
+/// A core made in this process and served on one end of a socket pair, an
+/// `Fsys` on the other: with no session, `help`, `words`, `completion` and
+/// `fs` ask the same tree a session serves, through the same client. Never
+/// stepped and never performing an effect: no shell, no file, no socket.
+const Here = struct {
+ const Engine = cloud9.fs.Server(pardes.ctlfs, .{ .fid_capacity = 32, .name_capacity = 255, .park_data_max = @import("9p.zig").msize - 23, .slot_capacity = 1 });
+ core: *pardes.Pardes,
+ engine: Engine,
+ fd: c_int,
+ in: [@import("9p.zig").msize]u8,
+ out: [2 * @import("9p.zig").msize]u8,
+ buf: [@import("9p.zig").msize]u8,
+
+ /// Answers what comes until the other end hangs up. A request the core
+ /// parks (a read of /log) stays parked: the client's deadline ends it.
+ fn serve(h: *Here) void {
+ while (true) {
+ const got = std.c.read(h.fd, &h.buf, h.buf.len);
+ if (got <= 0) return;
+ var bytes: []const u8 = h.buf[0..@intCast(got)];
+ while (true) {
+ bytes = bytes[h.engine.push(bytes)..];
+ while (h.engine.next()) |req| {
+ const r = h.core.serveFs(req);
+ h.engine.reply(&r, h.core.fsPayload(r));
+ }
+ const out = h.engine.output();
+ var sent: usize = 0;
+ while (sent < out.len) {
+ const n = std.c.write(h.fd, out[sent..].ptr, out.len - sent);
+ if (n <= 0) return;
+ sent += @intCast(n);
+ }
+ h.engine.wrote(out.len);
+ if (bytes.len == 0) break;
+ }
+ }
+ }
+};
+
+extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]std.c.fd_t) c_int;
+
+/// The tree a command reads: a session's, over its socket, or one made here.
+const Tree = struct {
+ f: cloud9.Fsys,
+ /// The core this process made, there being no session to ask.
+ here: ?*Here = null,
+
+ /// The session at `dial` (`Found.one`), or with none a core made here.
+ fn open(io: std.Io, gpa: std.mem.Allocator, dial: ?[]const u8) !*Tree {
+ const t = try gpa.create(Tree);
+ t.here = null;
+ if (dial) |d| {
+ const no_env = [_:null]?[*:0]const u8{};
+ try t.f.dial(io, &no_env, d, "pardes");
+ return t;
+ }
+ const h = try gpa.create(Here);
+ h.core = try pardes.Pardes.create(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ h.engine = .init(.{ .in = &h.in, .out = &h.out, .root = pardes.ctlfs.root });
+ var fds: [2]std.c.fd_t = undefined;
+ if (socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocketPair;
+ h.fd = fds[1];
+ (try std.Thread.spawn(.{}, Here.serve, .{h})).detach();
+ t.here = h;
+ try t.f.init(io, .{ .socket = .{ .handle = fds[0], .address = undefined } }, "pardes");
+ return t;
+ }
+
+ /// The whole file at `path`.
+ fn read(t: *Tree, gpa: std.mem.Allocator, path: []const u8) ![]const u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ try t.f.readFile(path, &out.writer);
+ return out.written();
+ }
+};
+
+/// The session a command acts on: `-s NAME` (a name, a socket's path or a
+/// dial), else $PARDES_9P, else the only one whose socket answers.
+const Found = union(enum) { none, one: []const u8, many: []const []const u8 };
+
+fn findSession(io: std.Io, arena: std.mem.Allocator, named: ?[]const u8) Found {
+ if (named) |n| {
+ if (std.mem.indexOfAny(u8, n, "/!") != null) return .{ .one = n };
+ var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined;
+ var buf: [ninep_io.sun_path_len]u8 = undefined;
+ const dir = ninep_io.socketDir(&dir_buf) orelse return .{ .one = n };
+ return .{ .one = arena.dupe(u8, ninep_io.socketPath(&buf, dir, n) orelse n) catch n };
+ }
+ if (std.c.getenv("PARDES_9P")) |d| return .{ .one = std.mem.span(d) };
+ const names = sessionNames(io, arena);
+ return switch (names.len) {
+ 0 => .none,
+ 1 => findSession(io, arena, names[0]),
+ else => .{ .many = names },
+ };
+}
+
+/// The names of the sessions whose sockets answer, in the socket directory.
+fn sessionNames(io: std.Io, arena: std.mem.Allocator) []const []const u8 {
+ var names: std.ArrayList([]const u8) = .empty;
+ var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined;
+ const path = ninep_io.socketDir(&dir_buf) orelse return &.{};
+ var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return &.{};
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (it.next(io) catch null) |e| {
+ const prefix = "pardes-9p-";
+ if (!std.mem.startsWith(u8, e.name, prefix) or !std.mem.endsWith(u8, e.name, ".sock")) continue;
+ const name = e.name[prefix.len .. e.name.len - ".sock".len];
+ if (name.len == 0 or !ninep_io.taken(name)) continue;
+ names.append(arena, arena.dupe(u8, name) catch continue) catch continue;
+ }
+ return names.items;
+}
+
+/// What a core made here can say of itself; the rest of the tree is a
+/// running session's.
+const offline = [_][]const u8{ "README", "commands", "ctl" };
+
+/// A /commands line: `Word[ arg] root|pane|both[ choices] -- what it does`.
+const Word = struct {
+ name: []const u8,
+ arg: bool,
+ scope: []const u8,
+ choices: []const u8,
+ doc: []const u8,
+
+ fn parse(line: []const u8) ?Word {
+ const cut = std.mem.indexOf(u8, line, " -- ");
+ var it = std.mem.tokenizeScalar(u8, line[0 .. cut orelse line.len], ' ');
+ var w: Word = .{ .name = it.next() orelse return null, .arg = false, .scope = "", .choices = "", .doc = if (cut) |c| line[c + 4 ..] else "" };
+ var next = it.next() orelse return null;
+ if (std.mem.eql(u8, next, "arg")) {
+ w.arg = true;
+ next = it.next() orelse return null;
+ }
+ w.scope = next;
+ w.choices = it.next() orelse "";
+ return w;
+ }
+
+ fn find(commands: []const u8, name: []const u8) ?Word {
+ var lines = std.mem.tokenizeScalar(u8, commands, '\n');
+ while (lines.next()) |line| if (parse(line)) |w| if (std.mem.eql(u8, w.name, name)) return w;
+ return null;
+ }
+
+ const groups = [_][]const u8{ "file", "column", "session", "jump", "text", "language", "theme", "help", "setting", "addon" };
+
+ /// Its group: the first key after the leader, else what it is.
+ fn group(w: Word) []const u8 {
+ if (std.mem.indexOf(u8, w.doc, " (addon ") != null and std.mem.endsWith(u8, w.doc, ")")) return "addon";
+ if (pardes.config.Runtime.find(w.name) != null) return "setting";
+ if (std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name)) |b| if (pardes.config.leader_path.get(b)) |p| switch (p[0]) {
+ 'f' => return "file",
+ 'c' => return "column",
+ 's' => return "session",
+ 'j' => return "jump",
+ 'l' => return "language",
+ 't' => return "theme",
+ 'h' => return "help",
+ else => {},
+ };
+ return if (std.mem.eql(u8, w.scope, "root")) "session" else "text";
+ }
+
+ /// `SPC c n`, its leader key, or empty.
+ fn leader(w: Word, buf: []u8) []const u8 {
+ const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name) orelse return "";
+ const path = pardes.config.leader_path.get(b) orelse return "";
+ var out: std.Io.Writer = .fixed(buf);
+ out.writeAll("SPC") catch return "";
+ for (path) |c| out.print(" {c}", .{c}) catch return "";
+ return out.buffered();
+ }
+};
+
+/// A command but new and attach, which go on to start or join a session.
+fn runCommand(init: std.process.Init, cmd: Cmd, all: []const [:0]const u8) noreturn {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ var out_buf: [4096]u8 = undefined;
+ var stdout = std.Io.File.stdout().writer(io, &out_buf);
+ const out = &stdout.interface;
+ // Its words as the shell has them: `-s` there is a word typed.
+ if (cmd == .completion) {
+ const status = completion(init, out, all, null);
+ out.flush() catch {};
+ std.process.exit(status);
+ }
+ // -s NAME and -p N anywhere after the command, but after `--`.
+ var session: ?[]const u8 = null;
+ var pane: ?[]const u8 = if (std.c.getenv("PARDES_PANE")) |p| std.mem.span(p) else null;
+ var rest: std.ArrayList([]const u8) = .empty;
+ var i: usize = 0;
+ while (i < all.len) : (i += 1) {
+ const a = all[i];
+ const value = i + 1 < all.len;
+ if (std.mem.eql(u8, a, "--")) {
+ for (all[i + 1 ..]) |r| rest.append(arena, r) catch die(io, "out of memory", .{});
+ break;
+ } else if ((std.mem.eql(u8, a, "-s") or std.mem.eql(u8, a, "--session")) and value) {
+ i += 1;
+ session = all[i];
+ } else if (std.mem.startsWith(u8, a, "--session=")) {
+ session = a["--session=".len..];
+ } else if (std.mem.eql(u8, a, "-p") and value and cmd == .do) {
+ i += 1;
+ pane = all[i];
+ } else rest.append(arena, a) catch die(io, "out of memory", .{});
+ }
+ const args = rest.items;
+ const status: u8 = switch (cmd) {
+ .new, .attach => unreachable,
+ .ps => manage(io, .list, ""),
+ .kill => {
+ if (args.len == 1 and std.mem.eql(u8, args[0], "--all")) manage(io, .killall, "");
+ if (args.len != 1 or args[0].len == 0) die(io, "kill needs a session's name (pardes ps lists them), or --all", .{});
+ manage(io, .kill, args[0]);
+ },
+ .version => version: {
+ out.writeAll(version_text) catch {};
+ out.print("9p 9P2000 msize {d}\n", .{@import("9p.zig").msize}) catch {};
+ break :version 0;
+ },
+ .skill => skill: {
+ out.writeAll(@embedFile("skill.txt")) catch {};
+ break :skill 0;
+ },
+ .help => help(init, out, args, session),
+ .words => listWords(init, out, args, session),
+ .do => doWord(init, args, session, pane),
+ .fs => fsVerb(init, out, args, session),
+ .completion => unreachable,
+ };
+ out.flush() catch {};
+ std.process.exit(status);
+}
+
+/// The tree a command that reads reads: a session's when one is named,
+/// inside, or the only one, else a core made here.
+fn readTree(init: std.process.Init, session: ?[]const u8) *Tree {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ const dial: ?[]const u8 = switch (findSession(io, arena, session)) {
+ .one => |d| d,
+ .none, .many => null,
+ };
+ return Tree.open(io, arena, dial) catch |err| {
+ if (dial) |d| die(io, "no session answers at {s} ({t}): pardes ps lists them", .{ d, err });
+ die(io, "a core made here would not start: {t}", .{err});
+ };
+}
+
+fn help(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ if (args.len == 0) {
+ writeFirstScreen(out) catch {};
+ return 0;
+ }
+ if (args.len > 1) die(io, "help takes one thing to say: a command, a builtin or a path", .{});
+ const what = args[0];
+ if (std.mem.eql(u8, what, "--all")) {
+ // This build's, never a session's: the reference prints it.
+ const t = Tree.open(io, arena, null) catch |err| die(io, "a core made here would not start: {t}", .{err});
+ writeHelpAll(out, t) catch |err| die(io, "help --all: {t}", .{err});
+ return 0;
+ }
+ if (std.meta.stringToEnum(Cmd, what)) |c| {
+ writeLeaf(out, c) catch {};
+ return 0;
+ }
+ const t = readTree(init, session);
+ const commands = t.read(arena, "commands") catch "";
+ if (Word.find(commands, what)) |w| {
+ var key_buf: [32]u8 = undefined;
+ const key = w.leader(&key_buf);
+ const scope = if (std.mem.eql(u8, w.scope, "root")) "the root ctl" else if (std.mem.eql(u8, w.scope, "both")) "a pane's ctl, or the root's" else "a pane's ctl";
+ out.print("{s} ({s}{s}{s}; {s})\n {s}\n", .{ w.name, scope, if (key.len == 0) "" else "; ", key, w.group(), w.doc }) catch {};
+ if (w.choices.len != 0) out.print(" one of: {s}\n", .{w.choices}) catch {};
+ out.print("\n pardes do {s}{s}\n", .{ w.name, if (w.arg) " [ARG]" else "" }) catch {};
+ return 0;
+ }
+ var err_buf: [1024]u8 = undefined;
+ var stderr = std.Io.File.stderr().writer(io, &err_buf);
+ var in: std.Io.Reader = .fixed("");
+ var said: std.Io.Writer.Allocating = .init(arena);
+ const status = cloud9.verbs.run(&t.f, &.{ "help", what }, &in, out, &said.writer);
+ if (status != 0) {
+ stderr.interface.print("pardes: help: {s} is not a command, a builtin (pardes words) or a file of the tree (pardes fs ls)\n", .{what}) catch {};
+ stderr.interface.flush() catch {};
+ }
+ return status;
+}
+
+fn listWords(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ if (args.len > 1) die(io, "words takes one group: {s}", .{"file column session jump text language theme help setting addon"});
+ const only: ?[]const u8 = if (args.len == 1) args[0] else null;
+ if (only) |g| for (Word.groups) |name| {
+ if (std.mem.eql(u8, name, g)) break;
+ } else die(io, "words: no group {s}: file column session jump text language theme help setting addon", .{g});
+ const t = readTree(init, session);
+ const commands = t.read(arena, "commands") catch |err| die(io, "words: /commands: {t}: {s}", .{ err, t.f.said() });
+ for (Word.groups) |g| {
+ if (only) |o| if (!std.mem.eql(u8, o, g)) continue;
+ var first = true;
+ var lines = std.mem.tokenizeScalar(u8, commands, '\n');
+ while (lines.next()) |line| {
+ const w = Word.parse(line) orelse continue;
+ if (!std.mem.eql(u8, w.group(), g)) continue;
+ if (first and only == null) out.print("{s}{s}:\n", .{ if (std.mem.eql(u8, g, Word.groups[0])) "" else "\n", g }) catch {};
+ first = false;
+ var buf: [64]u8 = undefined;
+ const left = std.fmt.bufPrint(&buf, "{s}{s}", .{ w.name, if (w.arg) " [ARG]" else "" }) catch w.name;
+ out.print(" {s}", .{left}) catch {};
+ out.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2) catch {};
+ out.print("{s}\n", .{w.doc}) catch {};
+ }
+ }
+ return 0;
+}
+
+fn doWord(init: std.process.Init, args: []const []const u8, session: ?[]const u8, pane: ?[]const u8) u8 {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ if (args.len == 0) die(io, "do needs a word: pardes do Newcol (pardes words lists them)", .{});
+ const dial = switch (findSession(io, arena, session)) {
+ .one => |d| d,
+ .none => die(io, "do: no session runs: start one (pardes new --detach=NAME), or name one (-s NAME)", .{}),
+ .many => |names| die(io, "do: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }),
+ };
+ const t = Tree.open(io, arena, dial) catch |err| die(io, "do: no session answers at {s} ({t}): pardes ps lists them", .{ dial, err });
+ const commands = t.read(arena, "commands") catch |err| die(io, "do: /commands: {t}: {s}", .{ err, t.f.said() });
+ const w = Word.find(commands, args[0]) orelse die(io, "do: no word {s} in this session: pardes words lists them", .{args[0]});
+ const at_pane = !std.mem.eql(u8, w.scope, "root") and pane != null;
+ if (std.mem.eql(u8, w.scope, "pane") and pane == null) die(io, "do: {s} is a pane's word: name the pane with -p N (pardes fs read index lists them)", .{w.name});
+ const ctl = if (at_pane) std.fmt.allocPrint(arena, "pane/{s}/ctl", .{pane.?}) catch unreachable else "ctl";
+ const line = std.mem.concat(arena, u8, &.{ std.mem.join(arena, " ", args) catch unreachable, "\n" }) catch unreachable;
+ t.f.writeFile(ctl, line) catch |err| switch (err) {
+ error.Refused => die(io, "do {s}: {s}", .{ w.name, t.f.said() }),
+ else => die(io, "do {s}: {s}: {t}", .{ w.name, ctl, err }),
+ };
+ return 0;
+}
+
+fn fsVerb(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ var err_buf: [1024]u8 = undefined;
+ var stderr = std.Io.File.stderr().writer(io, &err_buf);
+ defer stderr.interface.flush() catch {};
+ var in_buf: [64 * 1024]u8 = undefined;
+ var stdin = std.Io.File.stdin().readerStreaming(io, &in_buf);
+ const dial: ?[]const u8 = switch (findSession(io, arena, session)) {
+ .one => |d| d,
+ .none => null,
+ .many => |names| die(io, "fs: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }),
+ };
+ if (dial == null and args.len > 0) {
+ const verb = args[0];
+ const path = std.mem.trim(u8, if (args.len > 1) args[1] else "", "/");
+ const reads = std.mem.eql(u8, verb, "read");
+ if (std.mem.eql(u8, verb, "write") or std.mem.eql(u8, verb, "ask") or std.mem.eql(u8, verb, "follow"))
+ die(io, "fs {s}: no session runs to {s}: start one (pardes new --detach=NAME), then -s NAME", .{ verb, verb });
+ if (reads) for (offline) |name| {
+ if (std.mem.eql(u8, name, path)) break;
+ } else die(io, "fs read {s}: that is a running session's, and none runs: start one (pardes new --detach=NAME), then -s NAME; with none, README, commands and ctl say what they would", .{path});
+ }
+ const t = Tree.open(io, arena, dial) catch |err| {
+ if (dial) |d| die(io, "fs: no session answers at {s} ({t}): pardes ps lists them", .{ d, err });
+ die(io, "fs: a core made here would not start: {t}", .{err});
+ };
+ return cloud9.verbs.run(&t.f, args, &stdin.interface, out, &stderr.interface);
+}
+
+/// `pardes completion SHELL`: the script; `pardes completion -- WORDS`:
+/// what may follow, the last word being the one typed so far, a line each
+/// (`word\twhat it is`).
+fn completion(init: std.process.Init, out: *std.Io.Writer, args: []const [:0]const u8, session: ?[]const u8) u8 {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ if (args.len == 1) {
+ const Shell = enum { bash, fish, zsh };
+ const shell = std.meta.stringToEnum(Shell, args[0]) orelse die(io, "completion: no shell {s}: bash, fish or zsh", .{args[0]});
+ out.writeAll(switch (shell) {
+ .fish =>
+ \\# pardes completion fish: each word asked of pardes itself.
+ \\complete -c pardes -f -a '(pardes completion -- (commandline -opc)[2..-1] (commandline -ct))'
+ \\complete -c pardes -n 'test (count (commandline -opc)) -eq 1' -F
+ \\
+ ,
+ .bash =>
+ \\# pardes completion bash: each word asked of pardes itself.
+ \\_pardes() {
+ \\ local IFS=$'\n' line
+ \\ COMPREPLY=()
+ \\ while read -r line; do COMPREPLY+=("${line%%$'\t'*}"); done < <(pardes completion -- "${COMP_WORDS[@]:1:COMP_CWORD}")
+ \\ [ "$COMP_CWORD" -eq 1 ] && COMPREPLY+=($(compgen -f -- "${COMP_WORDS[COMP_CWORD]}"))
+ \\}
+ \\complete -o filenames -F _pardes pardes
+ \\
+ ,
+ .zsh =>
+ \\# pardes completion zsh: each word asked of pardes itself.
+ \\_pardes() {
+ \\ local -a said
+ \\ said=("${(@f)$(pardes completion -- "${(@)words[2,CURRENT]}")}")
+ \\ said=("${(@)said//:/\\:}")
+ \\ said=("${(@)said//$'\t'/:}")
+ \\ _describe pardes said
+ \\ (( CURRENT == 2 )) && _files
+ \\}
+ \\compdef _pardes pardes
+ \\
+ ,
+ }) catch {};
+ return 0;
+ }
+ if (args.len < 2 or !std.mem.eql(u8, args[0], "--"))
+ die(io, "completion needs a shell: bash, fish or zsh", .{});
+ const typed = args[1..];
+ const cur = typed[typed.len - 1];
+ const before = typed[0 .. typed.len - 1];
+ const Offer = struct {
+ fn one(w: *std.Io.Writer, prefix: []const u8, word: []const u8, what: []const u8) void {
+ if (!std.mem.startsWith(u8, word, prefix)) return;
+ w.print("{s}{s}{s}\n", .{ word, if (what.len == 0) "" else "\t", what }) catch {};
+ }
+ };
+ if (before.len == 0) {
+ for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line);
+ if (cur.len != 0 and cur[0] == '-') for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old) Offer.one(out, cur, @tagName(f), flags.get(f).doc);
+ return 0;
+ }
+ const cmd = std.meta.stringToEnum(Cmd, before[0]) orelse return 0;
+ switch (cmd) {
+ .new => for (std.enums.values(Flag)) |f| if (flags.get(f).group == .session) Offer.one(out, cur, @tagName(f), flags.get(f).doc),
+ .attach, .kill => if (before.len == 1) for (sessionNames(io, arena)) |name| Offer.one(out, cur, name, "a session"),
+ .completion => if (before.len == 1) for ([_][]const u8{ "bash", "fish", "zsh" }) |s| Offer.one(out, cur, s, ""),
+ .words => if (before.len == 1) for (Word.groups) |g| Offer.one(out, cur, g, ""),
+ .do, .help => if (before.len == 1) {
+ if (cmd == .help) for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line);
+ const t = readTree(init, session);
+ var lines = std.mem.tokenizeScalar(u8, t.read(arena, "commands") catch "", '\n');
+ while (lines.next()) |line| if (Word.parse(line)) |w| Offer.one(out, cur, w.name, w.doc);
+ if (cmd == .help) {
+ var said: std.Io.Writer.Allocating = .init(arena);
+ var in: std.Io.Reader = .fixed("");
+ _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer);
+ }
+ } else if (cmd == .do) {
+ const t = readTree(init, session);
+ if (Word.find(t.read(arena, "commands") catch "", before[1])) |w| if (w.choices.len != 0) {
+ var it = std.mem.tokenizeScalar(u8, w.choices, ',');
+ while (it.next()) |c| Offer.one(out, cur, c, "");
+ };
+ },
+ .fs => if (before.len == 1) {
+ var verbs = std.mem.tokenizeAny(u8, "ls read write ask follow stat help complete", " ");
+ while (verbs.next()) |v| Offer.one(out, cur, v, "");
+ } else if (before.len == 2) {
+ const t = readTree(init, session);
+ var said: std.Io.Writer.Allocating = .init(arena);
+ var in: std.Io.Reader = .fixed("");
+ _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer);
+ },
+ .ps, .skill, .version => {},
+ }
+ return 0;
+}
+
pub const main = nativeMain;
// glibc's struct termios is 60 bytes, Zig 0.17's std.c.termios the kernel's
@@ -396,36 +1147,111 @@ fn nativeMain(std_init: std.process.Init) !void {
var positional: ?[:0]const u8 = null;
var wait = false;
var i: usize = if (resuming) 2 else 1;
+ // A command's name first: new and attach go on to start or join a
+ // session, with the flags after them; the rest are done in `command`.
+ if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ .new => {
+ new_session = true;
+ i = 2;
+ },
+ .attach => {
+ const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
+ attach = if (named) args[2] else "";
+ i = if (named) 3 else 2;
+ },
+ else => runCommand(init, cmd, args[2..]),
+ };
while (i < args.len) : (i += 1) {
const a = args[i];
- const Flag = enum { @"--tty", @"-n", @"-l", @"--9p", @"--9p-tcp", @"--nested", @"-w", @"--wait", @"--detach", @"--attach", @"--ps", @"--kill-all", @"-h", @"--help", @"--version", @"--" };
- if (std.meta.stringToEnum(Flag, a)) |flag| switch (flag) {
+ if (a.len < 2 or a[0] != '-') {
+ // `-` is stdin, as for cat and vim: a text to show.
+ if (a.len == 0) badArgs(init.io, "an empty argument names nothing", .{});
+ if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{a});
+ session_only = false;
+ positional = a;
+ continue;
+ }
+ // `flags` says what each takes: nothing, the next argument (or
+ // after `=`), a value after `=`, or maybe one.
+ const eq = std.mem.indexOfScalar(u8, a, '=');
+ const flag = std.meta.stringToEnum(Flag, a[0 .. eq orelse a.len]) orelse badArgs(init.io, "no such option: {s}", .{a});
+ var value: ?[]const u8 = if (eq) |e| a[e + 1 ..] else null;
+ switch (flags.get(flag).takes) {
+ .none => if (value != null) badArgs(init.io, "{t} takes no value: {s}", .{ flag, a }),
+ .next => if (value == null and i + 1 < args.len) {
+ i += 1;
+ value = args[i];
+ },
+ .eq, .maybe => {},
+ }
+ switch (flag) {
.@"--tty" => explicit_tty = true,
.@"-n" => {
session_only = false;
new_session = true;
- i += 1;
- if (i >= args.len) badArgs(init.io, "-n needs a count after it: 1 or 3", .{});
- opts.shells = std.fmt.parseInt(u8, args[i], 10) catch
- badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{args[i]});
+ const count = value orelse badArgs(init.io, "-n needs a count after it: 1 or 3", .{});
+ opts.shells = std.fmt.parseInt(u8, count, 10) catch
+ badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{count});
},
.@"-l" => {
session_only = false;
new_session = true;
- i += 1;
- if (i >= args.len) badArgs(init.io, "-l needs the path of a dump to load", .{});
- opts.load_path = args[i];
+ opts.load_path = value orelse badArgs(init.io, "-l needs the path of a dump to load", .{});
+ },
+ .@"--tty-toggle" => {
+ session_only = false;
+ new_session = true;
+ const key = value orelse badArgs(init.io, "--tty-toggle needs a letter after it", .{});
+ opts.tty_toggle = parseCtrlKey(key) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{key});
},
- .@"--9p" => badArgs(init.io, "--9p needs a socket name: --9p=<name>", .{}),
- .@"--9p-tcp" => badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{}),
.@"--nested" => opts.nested = true,
.@"-w", .@"--wait" => wait = true,
- .@"--detach" => detach = "",
- .@"--attach" => attach = "",
+ .@"--9p" => {
+ new_session = true;
+ const name = value orelse badArgs(init.io, "--9p needs a socket name: --9p=<name>", .{});
+ if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null)
+ badArgs(init.io, "invalid 9P socket name: '{s}'", .{name});
+ opts.ninep_name = name;
+ },
+ .@"--9p-tcp" => {
+ new_session = true;
+ const dial = value orelse badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
+ if (!std.mem.startsWith(u8, dial, "tcp!"))
+ badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
+ _ = @import("9p_io.zig").networkAddress(dial, true) catch
+ badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
+ if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{});
+ opts.ninep_tcp = dial;
+ },
+ .@"--mount" => {
+ new_session = true;
+ const mount = value orelse badArgs(init.io, "--mount needs name=dial", .{});
+ const split = std.mem.indexOfScalar(u8, mount, '=') orelse
+ badArgs(init.io, "--mount needs name=dial", .{});
+ const name = mount[0..split];
+ const dial = mount[split + 1 ..];
+ if (dial.len == 0 or !@import("fs.zig").validMountName(name))
+ badArgs(init.io, "invalid mount name or dial: '{s}'", .{mount});
+ @import("9p_io.zig").Client.validateDial(dial) catch
+ badArgs(init.io, "invalid mount dial: '{s}'", .{dial});
+ for (mounts[0..mounts_len]) |existing| if (std.mem.eql(u8, existing.name, name))
+ badArgs(init.io, "duplicate mount name: '{s}'", .{name});
+ if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len});
+ mounts[mounts_len] = .{ .name = name, .dial = dial };
+ mounts_len += 1;
+ },
+ .@"--geometry" => opts.geometry = value orelse badArgs(init.io, "--geometry needs WxH[+X+Y]", .{}),
+ .@"--detach" => detach = value orelse "",
+ .@"--attach" => attach = value orelse "",
.@"--ps" => manage(init.io, .list, ""),
+ .@"--kill" => {
+ const name = value orelse "";
+ if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{});
+ manage(init.io, .kill, name);
+ },
.@"--kill-all" => manage(init.io, .killall, ""),
- .@"-h", .@"--help" => return std.Io.File.stdout().writeStreamingAll(init.io, help_text),
- .@"--version" => return std.Io.File.stdout().writeStreamingAll(init.io, version_text),
+ .@"-h", .@"--help" => runCommand(init, .help, &.{}),
+ .@"--version" => runCommand(init, .version, &.{}),
.@"--" => {
// The end of options: what follows is a name, `-dash.txt` too.
for (args[i + 1 ..]) |name| {
@@ -436,66 +1262,6 @@ fn nativeMain(std_init: std.process.Init) !void {
}
break;
},
- } else if (std.mem.eql(u8, a, "--tty-toggle") or std.mem.startsWith(u8, a, "--tty-toggle=")) {
- session_only = false;
- new_session = true;
- const key = if (a.len > "--tty-toggle".len) a["--tty-toggle=".len..] else next: {
- i += 1;
- if (i >= args.len) badArgs(init.io, "--tty-toggle needs a letter after it", .{});
- break :next args[i];
- };
- opts.tty_toggle = parseCtrlKey(key) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{key});
- } else if (std.mem.startsWith(u8, a, "--9p=")) {
- new_session = true;
- const name = a["--9p=".len..];
- if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null)
- badArgs(init.io, "invalid 9P socket name: '{s}'", .{name});
- opts.ninep_name = name;
- } else if (std.mem.startsWith(u8, a, "--9p-tcp=")) {
- new_session = true;
- const dial = a["--9p-tcp=".len..];
- if (!std.mem.startsWith(u8, dial, "tcp!"))
- badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
- _ = @import("9p_io.zig").networkAddress(dial, true) catch
- badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{});
- if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{});
- opts.ninep_tcp = dial;
- } else if (std.mem.startsWith(u8, a, "--mount=")) {
- new_session = true;
- const mount = a["--mount=".len..];
- const split = std.mem.indexOfScalar(u8, mount, '=') orelse
- badArgs(init.io, "--mount needs name=dial", .{});
- const name = mount[0..split];
- const dial = mount[split + 1 ..];
- if (dial.len == 0 or !@import("fs.zig").validMountName(name))
- badArgs(init.io, "invalid mount name or dial: '{s}'", .{mount});
- @import("9p_io.zig").Client.validateDial(dial) catch
- badArgs(init.io, "invalid mount dial: '{s}'", .{dial});
- for (mounts[0..mounts_len]) |existing| if (std.mem.eql(u8, existing.name, name))
- badArgs(init.io, "duplicate mount name: '{s}'", .{name});
- if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len});
- mounts[mounts_len] = .{ .name = name, .dial = dial };
- mounts_len += 1;
- } else if (std.mem.startsWith(u8, a, "--geometry=")) {
- opts.geometry = a["--geometry=".len..];
- } else if (std.mem.startsWith(u8, a, "--detach=")) {
- detach = a["--detach=".len..];
- } else if (std.mem.startsWith(u8, a, "--attach=")) {
- attach = a["--attach=".len..];
- } else if (std.mem.startsWith(u8, a, "--kill=")) {
- const name = a["--kill=".len..];
- if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{});
- manage(init.io, .kill, name);
- } else if (a.len > 0 and (a[0] != '-' or std.mem.eql(u8, a, "-")) and positional == null) {
- // `-` is stdin, as for cat and vim: a text to show.
- session_only = false;
- positional = a;
- } else if (a.len == 0) {
- badArgs(init.io, "an empty argument names nothing", .{});
- } else if (a[0] == '-') {
- badArgs(init.io, "no such option: {s}", .{a});
- } else {
- badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{a});
}
}
opts.tty_only = explicit_tty or session_only;
@@ -1071,6 +1837,52 @@ test "--wait finds the pane /index names a file by, spaces and all, and sees it
try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4));
}
+test "cli: docs/typ/command-line.txt is what pardes help --all prints" {
+ if (comptime !ninep_io.supported) return error.SkipZigTest;
+ var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const t = try Tree.open(std.testing.io, a, null);
+ defer t.f.close();
+ var out: std.Io.Writer.Allocating = .init(a);
+ try writeHelpAll(&out.writer, t);
+ var dir = try std.Io.Dir.cwd().openDir(std.testing.io, @import("doc_typ").dir, .{});
+ defer dir.close(std.testing.io);
+ const committed = try dir.readFileAlloc(std.testing.io, "command-line.txt", a, .limited(1 << 20));
+ if (!std.mem.eql(u8, committed, out.written())) {
+ std.debug.print("docs/typ/command-line.txt is stale: run `zig build builtins-json -Dplatform=tui --prefix <dir>`\n", .{});
+ return error.StaleCommandLine;
+ }
+}
+
+test "cli: the first screen names every command, and every flag has its help" {
+ var buf: [8192]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ try writeFirstScreen(&w);
+ for (std.enums.values(Cmd)) |c| {
+ var name: [32]u8 = undefined;
+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), try std.fmt.bufPrint(&name, "\n {t}", .{c})) != null);
+ }
+ w = .fixed(&buf);
+ try writeLeaf(&w, .new);
+ for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old)
+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), @tagName(f)) != null);
+}
+
+test "cli: a /commands line parses into its word" {
+ const w = Word.parse("Wrap root on,off -- Wrap long lines.").?;
+ try std.testing.expectEqualStrings("Wrap", w.name);
+ try std.testing.expect(!w.arg);
+ try std.testing.expectEqualStrings("root", w.scope);
+ try std.testing.expectEqualStrings("on,off", w.choices);
+ try std.testing.expectEqualStrings("Wrap long lines.", w.doc);
+ const e = Word.parse("Edit arg both -- Run sam's Edit.").?;
+ try std.testing.expect(e.arg);
+ try std.testing.expectEqualStrings("both", e.scope);
+ try std.testing.expectEqualStrings("addon", Word.parse("PdfFit arg pane -- Fit. (addon pdf)").?.group());
+ try std.testing.expectEqual(@as(?Word, null), Word.parse("Lonely"));
+}
+
test "tcgetattr writes nothing past a Zig termios" {
if (comptime !(builtin.os.tag == .linux and builtin.abi.isGnu())) return error.SkipZigTest;
const master = std.c.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(std.c.mode_t, 0));
diff --git a/src/skill.txt b/src/skill.txt
new file mode 100644
index 00000000..8ae6a15a
--- /dev/null
+++ b/src/skill.txt
@@ -0,0 +1,47 @@
+pardes, for an agent
+====================
+
+pardes is an editor (acme's mouse, helix's keys) and a terminal multiplexer,
+and every session is a file tree served over 9P: panes, columns, tags and
+the session are files. This guide is the judgement; the inventory is the
+binary's own and the session's, and it is always the one to trust:
+
+ pardes help the commands
+ pardes help PATH what the tree's README says of a file (pane, log...)
+ pardes words every builtin; pardes help WORD for one
+ pardes fs ls PATH what a session serves now
+
+Find the session
+ In a pane's shell, $PARDES_9P is its socket and $PARDES_PANE the pane:
+ every command below acts there. From outside, `pardes ps` lists the
+ sessions and -s NAME picks one. Never act on a session you did not start
+ or were not asked to touch: start your own, detached, and end it by name.
+
+ pardes new --detach=work & a session with no terminal, named work
+ pardes fs read index -s work a line per pane
+ pardes kill work done with it
+
+Recipes
+ n=$(pardes fs read pane/new -s work) make a pane, take its serial
+ pardes fs write pane/$n/name /tmp/x.txt -s work name it
+ printf 'text\n' | pardes fs write pane/$n/body -s work replace its text
+ pardes do Save -p $n -s work a pane's builtin
+ pardes do Newcol -s work a session's builtin
+ pardes fs write pane/$n/ctl 'Edit ,x/foo/c/bar/' -s work sam's Edit, one undo step
+ pardes fs ask pane/$n/look /etc/hosts:3 -s work open a file there; answers the pane it went to
+ pardes fs ask pane/$n/pty/run make -s work on a terminal pane: exit N, then the output
+ pardes fs follow log follow -s work events as they come (Ctrl-C ends it)
+ pardes fs read screen -s work what is drawn, as JSON
+
+Traps
+ A refusal is printed in the session's words and the exit is 1; through a
+ mount the same refusal is only EINVAL or EIO (grep '^err' log says why).
+ Pane words (Save Undo Del) go to a pane's ctl, settings and session words
+ to the root's: pardes do picks the ctl, pardes help WORD says which.
+ The root's look and exec act at the pane with the keyboard, which a person
+ may be using: write a pane's own look and exec instead.
+ addr is the pane's and moves on: each /re/ searches from the last.
+ Exit, Restore, Del and get refuse once over unsaved text; the same word
+ again discards it.
+ A read the session holds (log follow, an event file) waits for ever only
+ under fs follow; other calls give up after 30 s, saying so.
diff --git a/test/process.zig b/test/process.zig
index 67d883ca..1632387f 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -1105,7 +1105,7 @@ pub fn check(ok: bool, comptime what: []const u8, args: anytype) !void {
return error.TestUnexpectedResult;
}
-fn removeDir(path: []const u8) void {
+pub fn removeDir(path: []const u8) void {
var cmd: [4200]u8 = undefined;
if (std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{path}, 0)) |c| {
_ = system(c);
diff --git a/test/process/cli.zig b/test/process/cli.zig
new file mode 100644
index 00000000..083ba368
--- /dev/null
+++ b/test/process/cli.zig
@@ -0,0 +1,144 @@
+//! docs/typ/reference.typ, The pardes command <command-line>: the commands
+//! of a real pardes, against a session started for the case and against
+//! none (a core the command makes in its own process).
+const std = @import("std");
+const libc = std.c;
+const process = @import("../process.zig");
+const Conn = process.Conn;
+const has = process.has;
+const check = process.check;
+
+pub const cases = .{
+ .{ "cli: help prints the map, a command, a builtin and a file of the tree, with no session", helpOffline },
+ .{ "cli: fs with no session reads README, commands and ctl from a core made here, and says the rest is a session's", fsOffline },
+ .{ "cli: do, words and fs act on the session -s names, or the only one", againstSession },
+ .{ "cli: completion prints a script per shell and answers each word back", completion },
+ .{ "cli: version, skill, and the old spellings", versionAndOld },
+};
+
+extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8;
+
+/// A root of no session: HOME, runtime and config directories that hold none.
+fn emptyRoot(buf: *[64]u8) ![]const u8 {
+ const template = "/tmp/pardes-cli-XXXXXX";
+ @memcpy(buf[0..template.len], template);
+ buf[template.len] = 0;
+ _ = mkdtemp(buf[0..template.len :0]) orelse return error.NoTempDir;
+ return buf[0..template.len];
+}
+
+/// `pardes args...` in `root`: its exit, and stdout and stderr together.
+fn pardes(a: std.mem.Allocator, exe: [:0]const u8, root: []const u8, args: []const [:0]const u8) !process.Ran {
+ var argv: std.ArrayList([:0]const u8) = .empty;
+ try argv.appendSlice(a, &.{ "/bin/sh", "-c", "exec \"$0\" \"$@\" 1>&2", exe });
+ try argv.appendSlice(a, args);
+ return process.run(a, argv.items, .{ .root = root });
+}
+
+fn expectRan(r: process.Ran, code: c_int, said: []const u8, what: []const u8) !void {
+ try check(r.code == code and has(r.said, said), "{s}: exit {d}, not {d}; wanted '{s}' in: {s}", .{ what, r.code, code, said, r.said });
+}
+
+fn helpOffline(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [64]u8 = undefined;
+ const root = try emptyRoot(&buf);
+ defer process.removeDir(root);
+ const first = try pardes(a, exe, root, &.{"help"});
+ try expectRan(first, 0, "\nSessions:\n ps ", "help");
+ try expectRan(first, 0, "\nFiles:\n fs VERB [PATH]", "help");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "attach" }), 0, "\n pardes attach box:notes ", "help attach");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "new" }), 0, " --detach[=NAME]", "help new");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "fs" }), 0, "usage: fs ls [PATH]", "help fs");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "Newcol" }), 0, "Newcol (the root ctl; SPC c n; column)", "help Newcol");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "Save" }), 0, "pardes do Save", "help Save");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "pane/3/addr" }), 0, "pane/<n>/ name body tag", "help pane/3/addr");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "nowhere" }), 1, "is not a command, a builtin", "help nowhere");
+ const all = try pardes(a, exe, root, &.{ "help", "--all" });
+ try expectRan(all, 0, "== pardes help version", "help --all");
+ try expectRan(all, 0, "Pardes virtual filesystem", "help --all");
+ // The same map, by its old spelling.
+ try check(std.mem.eql(u8, first.said, (try pardes(a, exe, root, &.{"--help"})).said), "--help is not help", .{});
+}
+
+fn fsOffline(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [64]u8 = undefined;
+ const root = try emptyRoot(&buf);
+ defer process.removeDir(root);
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "ls" }), 0, "README\n", "fs ls");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "ls" }), 0, "pane/\n", "fs ls");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "README" }), 0, "Pardes virtual filesystem", "fs read README");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "commands" }), 0, "Newcol root -- ", "fs read commands");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "complete", "pa" }), 0, "pager\npane/\n", "fs complete pa");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "index" }), 1, "that is a running session's, and none runs", "fs read index");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "write", "ctl", "Newcol" }), 1, "no session runs to write", "fs write");
+ try expectRan(try pardes(a, exe, root, &.{ "do", "Newcol" }), 1, "no session runs: start one", "do");
+ const w = try pardes(a, exe, root, &.{"words"});
+ try expectRan(w, 0, "column:\n Newcol ", "words");
+ try expectRan(try pardes(a, exe, root, &.{ "words", "nosuch" }), 1, "no group nosuch", "words nosuch");
+}
+
+fn againstSession(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var d = try process.Detached.start(gpa, exe, "cli", .{});
+ defer d.deinit();
+ const c = try Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+ const cols = std.mem.count(u8, try c.read(a, "/layout"), "\n");
+ try expectRan(try pardes(a, exe, root, &.{ "do", "Newcol", "-s", "cli" }), 0, "", "do Newcol -s cli");
+ try check(std.mem.count(u8, try c.read(a, "/layout"), "\n") == cols + 1, "do Newcol made no column: {s}", .{try c.read(a, "/layout")});
+ // The only session, unnamed.
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "index" }), 0, "1 text 0 ", "fs read index");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "pane/1/body", "-s", "cli" }), 0, "initial\n", "fs read body");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "write", "pane/1/ctl", "bogus" }), 1, "fs: pane/1/ctl: ", "fs write refused");
+ try expectRan(try pardes(a, exe, root, &.{ "do", "Save" }), 1, "is a pane's word: name the pane with -p N", "do Save");
+ try expectRan(try pardes(a, exe, root, &.{ "do", "Nosuch" }), 1, "no word Nosuch in this session", "do Nosuch");
+ try expectRan(try pardes(a, exe, root, &.{ "words", "column" }), 0, "Newcol", "words column");
+ try expectRan(try pardes(a, exe, root, &.{ "help", "index" }), 0, "index a line per pane", "help index");
+ try expectRan(try pardes(a, exe, root, &.{ "fs", "read", "index", "-s", "nosuch" }), 1, "no session answers at ", "-s nosuch");
+}
+
+fn completion(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [64]u8 = undefined;
+ const root = try emptyRoot(&buf);
+ defer process.removeDir(root);
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "fish" }), 0, "pardes completion -- ", "completion fish");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "bash" }), 0, "complete -o filenames -F _pardes pardes", "completion bash");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "zsh" }), 0, "compdef _pardes pardes", "completion zsh");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "csh" }), 1, "no shell csh", "completion csh");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "--", "he" }), 0, "help\tthis, a command", "complete he");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "--", "do", "Newc" }), 0, "Newcol\t", "complete do Newc");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "--", "fs", "read", "pane/" }), 0, "pane/new\n", "complete fs read pane/");
+ try expectRan(try pardes(a, exe, root, &.{ "completion", "--", "new", "--det" }), 0, "--detach\t", "complete new --det");
+}
+
+fn versionAndOld(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [64]u8 = undefined;
+ const root = try emptyRoot(&buf);
+ defer process.removeDir(root);
+ const v = try pardes(a, exe, root, &.{"version"});
+ try expectRan(v, 0, "\nsemantics ", "version");
+ try expectRan(v, 0, "9p 9P2000 msize ", "version");
+ try check(std.mem.eql(u8, v.said, (try pardes(a, exe, root, &.{"--version"})).said), "--version is not version", .{});
+ try expectRan(try pardes(a, exe, root, &.{"skill"}), 0, "pardes help PATH", "skill");
+ // The daemon is off in a case's environment: both spellings say so.
+ try expectRan(try pardes(a, exe, root, &.{"ps"}), 1, "no pardes daemon is running", "ps");
+ try expectRan(try pardes(a, exe, root, &.{"--ps"}), 1, "no pardes daemon is running", "--ps");
+ try expectRan(try pardes(a, exe, root, &.{"kill"}), 1, "kill needs a session's name", "kill");
+ try expectRan(try pardes(a, exe, root, &.{"--kill"}), 1, "--kill needs a session's name", "--kill");
+ try expectRan(try pardes(a, exe, root, &.{"--tty=x"}), 1, "--tty takes no value", "--tty=x");
+}
diff --git a/test/process_test.zig b/test/process_test.zig
index 5876e005..aaa25a44 100644
--- a/test/process_test.zig
+++ b/test/process_test.zig
@@ -12,6 +12,7 @@ const tty = @import("tty.zig");
const files = .{
@import("process/builtins.zig"),
+ @import("process/cli.zig"),
@import("process/edit.zig"),
@import("process/flags.zig"),
@import("process/look_and_exec.zig"),