aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

commit fb688de9045d57940805010ea40deaf19762ff38
parent f9f1b05a36db8283d703e2600d1c7859f475bf0a
Author: shrub <maybeshrub@gmail.com>
Date:   Wed, 17 Jun 2026 17:08:44 +0000

use mdoc for manpages and add some manpages

Diffstat:
MMakefile | 3+--
Mcmd/linux/ctrlaltdel.c | 13++++++++-----
Mcmd/linux/depmod.c | 6++----
Mcmd/linux/eject.c | 7++++---
Mcmd/linux/fsfreeze.c | 11+++++++----
Mcmd/linux/hwclock.c | 17++++++++++-------
Mcmd/linux/insmod.c | 4++--
Mcmd/linux/modprobe.c | 29++++++++++-------------------
Mcmd/linux/mount.c | 21++++++++++++---------
Mcmd/linux/mountpoint.c | 8++++----
Mcmd/linux/rmmod.c | 8+++-----
Mcmd/linux/swaplabel.c | 6+++---
Mcmd/linux/swapoff.c | 9+++++----
Mcmd/linux/swapon.c | 13+++++++------
Mcmd/linux/switch_root.c | 9++++++---
Mcmd/linux/sysctl.c | 9++++++---
Mcmd/linux/tunctl.c | 8++++----
Mcmd/linux/umount.c | 14++++++++------
Mcmd/linux/unshare.c | 19++++++++++---------
Mcmd/net/host.c | 4++--
Mcmd/net/httpd.c | 6+++---
Mcmd/net/ifconfig.c | 4++--
Mcmd/net/ip.c | 4+++-
Mcmd/net/netcat.c | 8++++----
Mcmd/net/ping.c | 10+++++-----
Mcmd/net/tftp.c | 8++++----
Mcmd/net/wget.c | 16++++++++--------
Mcmd/posix/basename.c | 2+-
Mcmd/posix/cal.c | 16++++++++--------
Mcmd/posix/cat.c | 7+++----
Mcmd/posix/chgrp.c | 8++++----
Mcmd/posix/chown.c | 11++++++-----
Mcmd/posix/cmp.c | 4++--
Mcmd/posix/comm.c | 6+++---
Mcmd/posix/cp.c | 12++++++------
Mcmd/posix/cut.c | 32+++++++++++++++++++++++---------
Mcmd/posix/date.c | 7++++---
Mcmd/posix/df.c | 14+++++++-------
Mcmd/posix/du.c | 18+++++++++---------
Mcmd/posix/env.c | 6+++---
Mcmd/posix/expand.c | 4++--
Mcmd/posix/find.c | 6+++---
Mcmd/posix/fold.c | 10+++++-----
Mcmd/posix/getconf.c | 4++--
Mcmd/posix/grep.c | 42+++++++++++++++++++++---------------------
Mcmd/posix/head.c | 4++--
Mcmd/posix/id.c | 14+++++++-------
Mcmd/posix/join.c | 35++++++++++++++++++++++++++---------
Mcmd/posix/ln.c | 6+++---
Mcmd/posix/logger.c | 8++++----
Mcmd/posix/ls.c | 8++++----
Mcmd/posix/mesg.c | 2+-
Mcmd/posix/mkfifo.c | 2+-
Mcmd/posix/nice.c | 4++--
Mcmd/posix/nl.c | 65+++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcmd/posix/nohup.c | 2+-
Mcmd/posix/od.c | 61+++++++++++++++++++++++++++++++++++--------------------------
Mcmd/posix/paste.c | 4++--
Mcmd/posix/pathchk.c | 4++--
Mcmd/posix/pax.c | 61++++++++++++++++++++++++++++---------------------------------
Mcmd/posix/printf.c | 2+-
Mcmd/posix/ps.c | 14+++++++-------
Mcmd/posix/pwd.c | 4++--
Mcmd/posix/readlink.c | 4++--
Mcmd/posix/renice.c | 8++++----
Mcmd/posix/sed.c | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcmd/posix/sort.c | 56+++++++++++++++++++++++++++++++++-----------------------
Mcmd/posix/split.c | 10+++++-----
Mcmd/posix/tail.c | 10+++++-----
Mcmd/posix/tee.c | 4++--
Mcmd/posix/time.c | 4++--
Mcmd/posix/touch.c | 14+++++++-------
Mcmd/posix/tr.c | 10+++++-----
Mcmd/posix/uname.c | 12++++++------
Mcmd/posix/unexpand.c | 4++--
Mcmd/posix/uniq.c | 10+++++-----
Mcmd/posix/uuencode.c | 2+-
Mcmd/posix/wc.c | 8++++----
Mcmd/posix/who.c | 8++++----
Mcmd/posix/xargs.c | 43+++++++++++++++++++++++++++++--------------
Mcmd/pseudo/chroot.c | 2+-
Mcmd/pseudo/dmesg.c | 17+++++++++--------
Mcmd/pseudo/flock.c | 2+-
Mcmd/pseudo/free.c | 12++++++------
Mcmd/pseudo/getty.c | 2+-
Mcmd/pseudo/login.c | 7++++---
Mcmd/pseudo/md5sum.c | 6+++---
Mcmd/pseudo/mktemp.c | 8++++----
Mcmd/pseudo/pidof.c | 10+++++-----
Mcmd/pseudo/respawn.c | 2+-
Mcmd/pseudo/seq.c | 6+++---
Mcmd/pseudo/setsid.c | 2+-
Mcmd/pseudo/sha1sum.c | 6+++---
Mcmd/pseudo/sha224sum.c | 6+++---
Mcmd/pseudo/sha256sum.c | 6+++---
Mcmd/pseudo/sha384sum.c | 6+++---
Mcmd/pseudo/sha512-224sum.c | 6+++---
Mcmd/pseudo/sha512-256sum.c | 6+++---
Mcmd/pseudo/sha512sum.c | 6+++---
Mcmd/pseudo/tar.c | 24++++++++++++------------
Mcmd/pseudo/truncate.c | 10+++++-----
Mcmd/pseudo/which.c | 2+-
Mcmd/pseudo/xinstall.c | 20+++++++++++---------
Mcmd/xsi/mknod.c | 2+-
Mcmd/xsi/su.c | 10++++++----
Dscripts/mkman/djot/assemble.go | 1135-------------------------------------------------------------------------------
Dscripts/mkman/djot/ast.go | 250-------------------------------------------------------------------------------
Dscripts/mkman/djot/attr.go | 154-------------------------------------------------------------------------------
Dscripts/mkman/djot/block.go | 1224-------------------------------------------------------------------------------
Dscripts/mkman/djot/inline.go | 918-------------------------------------------------------------------------------
Dscripts/mkman/djot/marker.go | 306-------------------------------------------------------------------------------
Dscripts/mkman/djot/parser.go | 17-----------------
Mscripts/mkman/main.go | 411++-----------------------------------------------------------------------------
Ascripts/mkman/mdoc.go | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/mkman/page.go | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/mkman/parse.go | 951+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dscripts/mkman/troff.go | 248-------------------------------------------------------------------------------
117 files changed, 2030 insertions(+), 5192 deletions(-)

diff --git a/Makefile b/Makefile @@ -685,7 +685,7 @@ box: $(LIB) .PHONY: man clean -scripts/mkman/mkman: scripts/mkman/main.go scripts/mkman/troff.go +scripts/mkman/mkman: scripts/mkman/main.go scripts/mkman/page.go scripts/mkman/parse.go scripts/mkman/mdoc.go cd scripts/mkman && go build -o mkman . man: scripts/mkman/mkman @@ -902,4 +902,3 @@ cmd/dev/cc/cpp: cmd/dev/cc/cpp.o $(CPP_OBJ) $(LIB) - diff --git a/cmd/linux/ctrlaltdel.c b/cmd/linux/ctrlaltdel.c @@ -15,20 +15,23 @@ usage(void) eprintf("usage: %s -h | -s\n", argv0); } -// ?man ctrlaltdel: set ctrl-alt-del function -// ?man arguments: -h | -s -// ?man set the behavior of the ctrl-alt-del key combination +// ?man ctrlaltdel: toggle Ctrl-Alt-Del behaviour +// ?man synopsis: -h +// ?man synopsis: -s +// ?man ctrlaltdel toggles the function of Ctrl-Alt-Del based on the two choices given in linux/kernel/sys.c. +// ?man Hard reset reboots the computer immediately without calling sync. +// ?man Soft reset sends SIGINT to init. int main(int argc, char *argv[]) { int hflag = 0, sflag = 0, cmd; ARGBEGIN { - // ?man -h: suppress headers or print help + // ?man -h: Set to hard reset. case 'h': hflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: Set to soft reset. case 's': sflag = 1; break; diff --git a/cmd/linux/depmod.c b/cmd/linux/depmod.c @@ -263,8 +263,6 @@ usage(void) // ?man depmod: generate modules.dep and map files // ?man arguments: version // ?man depmod generates modules.dep containing dependency information for modprobe -// ?man // ?man -n: dry run print results to stdout instead of writing files -// ?man // ?man -b basedir: use basedir as prefix for module directories int main(int argc, char *argv[]) { @@ -281,11 +279,11 @@ main(int argc, char *argv[]) FILE *f_dep, *f_alias, *f_sym; ARGBEGIN { - // ?man -n: specify n option + // ?man -n: Dry run; print results to stdout instead of writing files. case 'n': nflag = 1; break; - // ?man -b:dir: specify b option + // ?man -b:dir: Use dir as the prefix for module directories. case 'b': basedir = EARGF(usage()); break; diff --git a/cmd/linux/eject.c b/cmd/linux/eject.c @@ -48,14 +48,15 @@ usage(void) eprintf("usage: %s [-t] [device ...]\n", argv0); } -// ?man eject: eject removable media +// ?man eject: control device trays // ?man arguments: device ... -// ?man eject optical discs or other removable storage media +// ?man eject opens the tray of each device. +// ?man If no device is given eject opens the tray of /dev/sr0. int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -t: sort or specify timestamp + // ?man -t: Close instead of open the tray. case 't': tflag = 1; break; diff --git a/cmd/linux/fsfreeze.c b/cmd/linux/fsfreeze.c @@ -22,8 +22,11 @@ usage(void) } // ?man fsfreeze: suspend access to a filesystem -// ?man arguments: (-f | -u) mountpoint -// ?man freeze or unfreeze a filesystem to allow safe backups +// ?man arguments: mountpoint +// ?man fsfreeze suspends and resumes access to a filesystem. +// ?man fsfreeze is intended to be used with hardware RAID devices that support the creation of snapshots. +// ?man The mountpoint argument is the pathname of the directory where the filesystem is mounted. +// ?man The filesystem must be mounted to be frozen. int main(int argc, char *argv[]) { @@ -33,11 +36,11 @@ main(int argc, char *argv[]) int fd; ARGBEGIN { - // ?man -f: force the operation + // ?man -f: Freeze the filesystem mounted at mountpoint. case 'f': fflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: Unfreeze the filesystem mounted at mountpoint. case 'u': uflag = 1; break; diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c @@ -116,7 +116,11 @@ usage(void) // ?man hwclock: query or set the hardware clock // ?man arguments: dev -// ?man view or adjust the hardware real time clock +// ?man hwclock is a tool for accessing the hardware clock. +// ?man You can display the current time, set the hardware clock from the System Time, or set the System Time from the hardware clock. +// ?man It currently only works with UTC. +// ?man You can use dev to specify the RTC device node absolute path. +// ?man By default it will use /dev/rtc. int main(int argc, char *argv[]) { @@ -126,19 +130,19 @@ main(int argc, char *argv[]) int wflag = 0; ARGBEGIN { - // ?man -r: operate recursively + // ?man -r: Read the hardware clock and print the time on stdout. case 'r': rflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: Set the system time from the hardware clock. case 's': sflag = 1; break; - // ?man -w: wait for completion + // ?man -w: Set the hardware clock to the system time. case 'w': wflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: Use UTC. This is the default option. case 'u': break; default: @@ -165,4 +169,4 @@ main(int argc, char *argv[]) systohc(dev); return 0; -} -\ No newline at end of file +} diff --git a/cmd/linux/insmod.c b/cmd/linux/insmod.c @@ -17,8 +17,8 @@ usage(void) } // ?man insmod: insert a module into the Linux kernel -// ?man arguments: filename [args... -// ?man insmod inserts a kernel module from filename into the running kernel +// ?man arguments: filename [args ...] +// ?man insmod inserts the module specified by filename into the kernel. It does not handle module dependencies. int main(int argc, char *argv[]) { diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -535,7 +535,7 @@ usage(void) } // ?man modprobe: add or remove modules from the Linux kernel -// ?man arguments: module [symbol=value ... +// ?man arguments: module [symbol=value ...] // ?man modprobe loads or removes kernel modules from the running system. // ?man It reads modules.dep, modules.alias, and modules.symbols from the appropriate // ?man /lib/modules/release directory to resolve module names and dependencies, @@ -551,48 +551,39 @@ main(int argc, char *argv[]) int i, ret = 0; ARGBEGIN { - // ?man -a: specify a option + // ?man -a: Load all modules named on the command line rather than stopping after the first. case 'a': - // ?man -a: Load all modules named on the command line (rather than stopping after the first). aflag = 1; break; - // ?man -r: specify r option + // ?man -r: Remove the named modules from the kernel. Dependencies are not automatically removed. case 'r': - // ?man -r: Remove the named modules from the kernel. Dependencies are not automatically removed. rflag = 1; break; - // ?man -q: specify q option + // ?man -q: Quiet mode. Suppress error messages. case 'q': - // ?man -q: Quiet mode. Suppress error messages. qflag = 1; break; - // ?man -v: specify v option + // ?man -v: Verbose mode. Print each action taken. case 'v': - // ?man -v: Verbose mode. Print each action taken. vflag = 1; break; - // ?man -l: specify l option + // ?man -l: List available modules matching the optional pattern, a fnmatch(3) glob. case 'l': - // ?man -l: List available modules matching the optional _pattern_ (a fnmatch(3) glob). lflag = 1; break; #if FEATURE_MODPROBE_SHOW_DEPENDS - // ?man -D: specify D option + // ?man -D: Print the sequence of insmod commands that would be used to load the module, without actually loading anything. case 'D': - // ?man -D: Print the sequence of insmod commands that would be used to load the module, without actually loading anything. Dflag = 1; break; #endif #if FEATURE_MODPROBE_BLACKLIST - // ?man -b: specify b option + // ?man -b: Skip modules listed as blacklist in /etc/modprobe.d/. case 'b': - // ?man -b: Skip modules listed as blacklist in /etc/modprobe.d/. bflag = 1; break; #endif #if FEATURE_MODPROBE_SYSLOG - // ?man -s: specify s option + // ?man -s: Log messages to syslog(3) facility LOG_DAEMON instead of standard error. case 's': - // ?man -s: Log messages to syslog(3) (facility LOG_DAEMON) instead of standard error. sflag = 1; break; #endif #if FEATURE_MODPROBE_DIR_OVERRIDE - // ?man -d:file: specify d option + // ?man -d:dir: Use dir as the base directory for module files instead of /lib/modules/release. case 'd': - // ?man -d dir: Use dir as the base directory for module files instead of /lib/modules/release. strlist_append(&moddirs, EARGF(usage())); break; #endif default: diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -191,8 +191,8 @@ usage(void) } // ?man mount: mount a filesystem -// ?man arguments: source] [target -// ?man mount a filesystem to the directory tree +// ?man arguments: [source] [target] +// ?man mount attaches the filesystem specified to the filesystem hierarchy. The umount command will detach it again. int main(int argc, char *argv[]) { @@ -205,32 +205,35 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -B: specify option flag + // ?man -B: Remount a subtree somewhere else (so that its contents are visible in both places). case 'B': argflags |= MS_BIND; break; - // ?man -M: specify option flag + // ?man -M: Move a subtree to some other place. case 'M': argflags |= MS_MOVE; break; - // ?man -R: operate recursively on directories + // ?man -R: Remount a subtree and all possible submounts somewhere else (so that its contents are available in both places). case 'R': argflags |= MS_REC; break; - // ?man -a: print or show all entries + // ?man -a: Mount all filesystems mentioned in /etc/fstab. case 'a': aflag = 1; break; - // ?man -o:str: specify output file + // ?man -o:options: Specify a comma separated string of filesystem specific options. case 'o': estrlcat(fsopts, EARGF(usage()), sizeof(fsopts)); parseopts(fsopts, &flags, data, sizeof(data)); break; - // ?man -t:str: sort or specify timestamp + // ?man -t:fstype: Set the filesystem type. More than one type may be specified in a comma separated list. + // ?man The list of file system types can be prefixed with "no" to specify the file system types for which action should not be taken. + // ?man For example, mount -a -t nonfs,ext4 mounts all file systems except those of type NFS and EXT4. + // ?man mount will attempt to execute a program in your PATH mount.XXX where XXX is replaced by the type name. For example, NFS file systems are mounted by the program mount.nfs. case 't': types = EARGF(usage()); break; - // ?man -n: print line numbers or counts + // ?man -n: Mount without writing in /etc/mtab. This is the default action. case 'n': break; default: diff --git a/cmd/linux/mountpoint.c b/cmd/linux/mountpoint.c @@ -21,7 +21,7 @@ usage(void) // ?man mountpoint: check if a directory is a mountpoint // ?man arguments: target -// ?man determine if a directory is a mountpoint +// ?man mountpoint checks if the directory is mentioned in the /proc/mounts file. int main(int argc, char *argv[]) { @@ -32,15 +32,15 @@ main(int argc, char *argv[]) struct stat st1, st2; ARGBEGIN { - // ?man -d: specify directory + // ?man -d: Print the major/minor device number of the filesystem on stdout. case 'd': dflag = 1; break; - // ?man -q: quiet mode; suppress output + // ?man -q: Be quiet, don't print anything. case 'q': qflag = 1; break; - // ?man -x: hex format or match whole lines + // ?man -x: Print the major/minor device number of the device on stdout. case 'x': xflag = 1; break; diff --git a/cmd/linux/rmmod.c b/cmd/linux/rmmod.c @@ -18,9 +18,7 @@ usage(void) // ?man rmmod: remove a module from the Linux kernel // ?man arguments: module... -// ?man rmmod removes a kernel module from the running kernel -// ?man // ?man -f: force removal of a module even if it is busy or in use -// ?man // ?man -w: wait for the module to become unused before removing +// ?man rmmod removes one or more modules from the kernel. int main(int argc, char *argv[]) { @@ -29,11 +27,11 @@ main(int argc, char *argv[]) int flags = O_NONBLOCK; ARGBEGIN { - // ?man -f: specify f option + // ?man -f: This option can be extremely dangerous: it has no effect unless CONFIG_MODULE_FORCE_UNLOAD was set when the kernel was compiled. With this option, you can remove modules which are being used, or which are not designed to be removed, or have been marked as unsafe. case 'f': flags |= O_TRUNC; break; - // ?man -w: specify w option + // ?man -w: Normally, rmmod will refuse to unload modules which are in use. With this option, rmmod will isolate the module, and wait until the module is no longer used. Noone new will be able to use the module, but it's up to you to make sure the current users eventually finish with it. case 'w': flags &= ~O_NONBLOCK; break; diff --git a/cmd/linux/swaplabel.c b/cmd/linux/swaplabel.c @@ -24,9 +24,9 @@ usage(void) eprintf("usage: %s [-L label] device\n", argv0); } -// ?man swaplabel: print or change swap label +// ?man swaplabel: set the label of a swap filesystem // ?man arguments: device -// ?man display or modify the label and uuid of a swap device +// ?man swaplabel is used to change the label of a swap device or file. int main(int argc, char *argv[]) { @@ -38,7 +38,7 @@ main(int argc, char *argv[]) int i; ARGBEGIN { - // ?man -L:str: specify option flag + // ?man -L:label: Change the label. case 'L': setlabel = 1; label = EARGF(usage()); diff --git a/cmd/linux/swapoff.c b/cmd/linux/swapoff.c @@ -16,9 +16,10 @@ usage(void) eprintf("usage: %s -a | device\n", argv0); } -// ?man swapoff: disable swap devices -// ?man arguments: -a | device -// ?man disable paging and swapping on specified devices +// ?man swapoff: disable devices and files for paging and swapping +// ?man synopsis: -a +// ?man synopsis: device +// ?man swapoff disables swapping on the specified devices and files. int main(int argc, char *argv[]) { @@ -29,7 +30,7 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: Disable swapping on all known swap devices and files as found in /etc/fstab. case 'a': all = 1; break; diff --git a/cmd/linux/swapon.c b/cmd/linux/swapon.c @@ -16,9 +16,10 @@ usage(void) eprintf("usage: %s [-dp] -a | device\n", argv0); } -// ?man swapon: enable swap devices -// ?man arguments: -a | device -// ?man enable paging and swapping on specified devices +// ?man swapon: enable devices and files for paging and swapping +// ?man synopsis: [-d] [-p] -a +// ?man synopsis: [-d] [-p] device +// ?man swapon is used to specify devices on which paging and swapping are to take place. int main(int argc, char *argv[]) { @@ -30,15 +31,15 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: Make all devices marked as "swap" in /etc/fstab available, except for those with the "noauto" option. case 'a': all = 1; break; - // ?man -d: specify directory + // ?man -d: Discard freed swap pages before they are reused. case 'd': flags |= SWAP_FLAG_DISCARD; break; - // ?man -p: preserve file attributes + // ?man -p: Set higher priority than the default for the new swap area. case 'p': flags |= SWAP_FLAG_PREFER; break; diff --git a/cmd/linux/switch_root.c b/cmd/linux/switch_root.c @@ -67,8 +67,11 @@ usage(void) } // ?man switch_root: switch to another root filesystem -// ?man arguments: newroot] [init] (PID 1) -// ?man switch to another filesystem as the root of the mount tree +// ?man arguments: [newroot] [init] +// ?man switch_root removes all files and directories on the current root filesystem and overmounts it with newroot. +// ?man If a console is specified, redirect stdio and stderr to it. +// ?man After the switch, execute init. +// ?man switch_root can only be run as PID 1 in an initramfs or tmpfs with a regular and executable /sbin/init. int main(int argc, char *argv[]) { @@ -78,7 +81,7 @@ main(int argc, char *argv[]) struct statfs stfs; ARGBEGIN { - // ?man -c:str: print count or perform stdout action + // ?man -c:console: Redirect stdio and stderr to console after switching to newroot. case 'c': console = EARGF(usage()); break; diff --git a/cmd/linux/sysctl.c b/cmd/linux/sysctl.c @@ -160,9 +160,12 @@ usage(void) eprintf("usage: %s [-p file] variable[=value]...\n", argv0); } -// ?man sysctl: configure kernel parameters +// ?man sysctl: configure kernel parameters at runtime // ?man arguments: variable[=value]... -// ?man view and modify kernel parameters at runtime +// ?man sysctl modifies kernel parameters at runtime. +// ?man The parameters available are those listed under /proc/sys. +// ?man Procfs is required for sysctl support in Linux. +// ?man You can use sysctl to both read and write sysctl data. int main(int argc, char *argv[]) { @@ -174,7 +177,7 @@ main(int argc, char *argv[]) int r = 0; ARGBEGIN { - // ?man -p:file: preserve file attributes + // ?man -p:file: Load the sysctl key=value pairs from file. case 'p': file = EARGF(usage()); break; diff --git a/cmd/linux/tunctl.c b/cmd/linux/tunctl.c @@ -43,21 +43,21 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -d: specify directory + // ?man -d: Clear persistence on the interface. case 'd': dflag = 1; tflag = 0; break; - // ?man -t: sort or specify timestamp + // ?man -t: Make the interface persistent. case 't': tflag = 1; dflag = 0; break; - // ?man -T: specify option flag + // ?man -T: Create a TAP device instead of a TUN device. case 'T': Tflag = 1; break; - // ?man -u:str: unbuffered output + // ?man -u:owner: Set the owner of the persistent interface. case 'u': owner = EARGF(usage()); break; diff --git a/cmd/linux/umount.c b/cmd/linux/umount.c @@ -127,7 +127,9 @@ usage(void) // ?man umount: unmount filesystems // ?man arguments: target... -// ?man unmount a filesystem from the directory tree +// ?man umount detaches the target filesystem or filesystems. +// ?man A file system is specified by giving the directory where it has been mounted. +// ?man Giving the special device on which the file system lives may also work, but is obsolete, mainly because it will fail in case this device was mounted on more than one directory. int main(int argc, char *argv[]) { @@ -140,23 +142,23 @@ main(int argc, char *argv[]) #endif ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: All of the file systems described in /proc/mounts are unmounted. The proc filesystem is not unmounted. case 'a': aflag = 1; break; - // ?man -f: force the operation + // ?man -f: Force unmount (in case of an unreachable NFS server). case 'f': flags |= MNT_FORCE; break; - // ?man -l: list in long format + // ?man -l: Lazy unmount. Detach the filesystem from the fs hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. case 'l': flags |= MNT_DETACH; break; - // ?man -n: print line numbers or counts + // ?man -n: Unmount without writing in /etc/mtab. This is the default action. case 'n': break; #if FEATURE_UMOUNT_OPTIONS - // ?man -O:str: specify option flag + // ?man -O:opts: Only act on mounts matching opts. case 'O': oflag = EARGF(usage()); break; diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c @@ -15,36 +15,37 @@ usage(void) eprintf("usage: %s [-muinpU] cmd [args...]\n", argv0); } -// ?man unshare: run program in new namespaces -// ?man arguments: cmd [args... -// ?man run a program with some namespaces unshared from the parent +// ?man unshare: run program with some namespaces unshared from parent +// ?man arguments: cmd [args ...] +// ?man unshare unshares the indicated namespaces from the parent process and then executes the specified program. +// ?man The namespaces to be unshared are indicated via options. int main(int argc, char *argv[]) { int flags = 0; ARGBEGIN { - // ?man -m: specify mode or limit + // ?man -m: Unshare the mount namespace, so that the calling process has a private copy of its namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWNS flag. case 'm': flags |= CLONE_NEWNS; break; - // ?man -u: unbuffered output + // ?man -u: Unshare the UTS IPC namespace, so that the calling process has a private copy of the UTS namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWUTS flag. case 'u': flags |= CLONE_NEWUTS; break; - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: Unshare the System V IPC namespace, so that the calling process has a private copy of the System V IPC namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWIPC flag. case 'i': flags |= CLONE_NEWIPC; break; - // ?man -n: print line numbers or counts + // ?man -n: Unshare the network namespace, so that the calling process is moved into a new network namespace which is not shared with any previously existing process. This flag has the same effect as the clone CLONE_NEWNET flag. case 'n': flags |= CLONE_NEWNET; break; - // ?man -p: preserve file attributes + // ?man -p: Create the process in a new PID namespace. This flag has the same effect as the clone CLONE_NEWPID flag. case 'p': flags |= CLONE_NEWPID; break; - // ?man -U: specify option flag + // ?man -U: The process will have a distinct set of UIDs, GIDs and capabilities. case 'U': flags |= CLONE_NEWUSER; break; diff --git a/cmd/net/host.c b/cmd/net/host.c @@ -258,7 +258,7 @@ parse_response(const unsigned char *resp, int resp_len, const char *query_name) } // ?man host: dns lookup utility -// ?man arguments: name [server +// ?man arguments: name [server] // ?man look up hostnames and IP addresses using dns int main(int argc, char *argv[]) @@ -274,7 +274,7 @@ main(int argc, char *argv[]) int i, r; ARGBEGIN { - // ?man -t:str: sort or specify timestamp + // ?man -t:type: Query DNS records of the given type. case 't': tflag = EARGF(usage()); break; diff --git a/cmd/net/httpd.c b/cmd/net/httpd.c @@ -262,15 +262,15 @@ main(int argc, char *argv[]) char *enc; ARGBEGIN { - // ?man -e:str: specify expression or pattern + // ?man -e:str: Print the URL-encoded form of str and exit. case 'e': eflag = EARGF(usage()); break; - // ?man -d:str: specify directory + // ?man -d:str: Print the URL-decoded form of str and exit. case 'd': dflag = EARGF(usage()); break; - // ?man -v: verbose mode; show progress + // ?man -v: Accepted for compatibility; no effect. case 'v': break; default: diff --git a/cmd/net/ifconfig.c b/cmd/net/ifconfig.c @@ -98,7 +98,7 @@ list_interfaces(int all) } // ?man ifconfig: configure network interfaces -// ?man arguments: interface [action ... +// ?man arguments: interface [action ...] // ?man configure network interface parameters and view stats int main(int argc, char *argv[]) @@ -118,7 +118,7 @@ main(int argc, char *argv[]) unsigned int mask; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: Show all interfaces, including those that are down. case 'a': aflag = 1; break; diff --git a/cmd/net/ip.c b/cmd/net/ip.c @@ -346,7 +346,9 @@ do_route(int argc, char *argv[]) } // ?man ip: show or configure routing and devices -// ?man arguments: addr | link | route] [args... +// ?man synopsis: addr [args ...] +// ?man synopsis: link [args ...] +// ?man synopsis: route [args ...] // ?man configure and view network devices, routing, and tunnels // ?man ## COMMANDS // ?man ### addr [show | list [dev <device>]] diff --git a/cmd/net/netcat.c b/cmd/net/netcat.c @@ -49,7 +49,7 @@ resolve(const char *host, const char *port, int family, int socktype, } // ?man netcat: read and write data across network connections -// ?man arguments: host] [port +// ?man arguments: [host] [port] // ?man arbitrary data transmission over tcp or udp int main(int argc, char *argv[]) @@ -70,15 +70,15 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -l: list in long format + // ?man -l: Listen for an incoming connection. case 'l': lflag = 1; break; - // ?man -p:str: preserve file attributes + // ?man -p:port: Use port as the local port. case 'p': local_port = EARGF(usage()); break; - // ?man -u: unbuffered output + // ?man -u: Use UDP instead of TCP. case 'u': uflag = 1; break; diff --git a/cmd/net/ping.c b/cmd/net/ping.c @@ -141,23 +141,23 @@ main(int argc, char *argv[]) socklen_t fromlen; ARGBEGIN { - // ?man -c:str: print count or perform stdout action + // ?man -c:count: Stop after sending count requests. case 'c': cflag = EARGF(usage()); break; - // ?man -i:str: interactive mode or prompt for confirmation + // ?man -i:interval: Wait interval seconds between requests. case 'i': iflag = EARGF(usage()); break; - // ?man -s:str: silent mode or print summary + // ?man -s:size: Send size bytes of payload data. case 's': sflag = EARGF(usage()); break; - // ?man -t:str: sort or specify timestamp + // ?man -t:ttl: Set the IP time-to-live. case 't': tflag = EARGF(usage()); break; - // ?man -w:str: wait for completion + // ?man -w:deadline: Stop after deadline seconds. case 'w': wflag = EARGF(usage()); break; diff --git a/cmd/net/tftp.c b/cmd/net/tftp.c @@ -261,19 +261,19 @@ main(int argc, char *argv[]) int ret; ARGBEGIN { - // ?man -h:str: suppress headers or print help + // ?man -h:host: Connect to host. case 'h': host = EARGF(usage()); break; - // ?man -p:str: preserve file attributes + // ?man -p:port: Use port instead of the default tftp service. case 'p': port = EARGF(usage()); break; - // ?man -x: hex format or match whole lines + // ?man -x: Download file from the server. case 'x': fn = getfile; break; - // ?man -c: print count or perform stdout action + // ?man -c: Upload file to the server. case 'c': fn = putfile; break; diff --git a/cmd/net/wget.c b/cmd/net/wget.c @@ -327,35 +327,35 @@ main(int argc, char *argv[]) size_t i; ARGBEGIN { - // ?man -O:str: specify output file path + // ?man -O:str: Write output to str instead of the default file name. case 'O': Oflag = EARGF(usage()); break; - // ?man -P:str: specify output directory prefix + // ?man -P:str: Write output files under directory str. case 'P': Pflag = EARGF(usage()); break; - // ?man -T:num: set network read and connect timeout + // ?man -T:num: Set the network read and connect timeout to num seconds. case 'T': timeout_sec = estrtonum(EARGF(usage()), 0, 100000); break; - // ?man -U:str: set User-Agent header + // ?man -U:str: Set the User-Agent header to str. case 'U': user_agent = EARGF(usage()); break; - // ?man -c: continue retrieval of aborted transfer + // ?man -c: Continue retrieval of an aborted transfer. case 'c': cflag = 1; break; - // ?man -q: quiet mode to suppress stderr output + // ?man -q: Quiet mode. Suppress stderr output. case 'q': qflag = 1; break; - // ?man -S: print server response headers to stderr + // ?man -S: Print server response headers to stderr. case 'S': Sflag = 1; break; - // ?man --: specify - option + /* long options handle TLS verification, extra headers, POST data, and spider mode */ case '-': if (strcmp(argv[0], "-no-check-certificate") == 0) { no_check_certificate = 1; diff --git a/cmd/posix/basename.c b/cmd/posix/basename.c @@ -14,7 +14,7 @@ usage(void) } // ?man basename: strip directory and suffix from filenames -// ?man arguments: path [suffix +// ?man arguments: path [suffix] // ?man print filename with leading directories and optional suffix removed int main(int argc, char *argv[]) diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c @@ -179,11 +179,11 @@ main(int argc, char *argv[]) ARGBEGIN { #ifdef FEATURE_CAL_EXT - // ?man -1: specify option flag + // ?man -1: print the current month case '1': nmons = 1; break; - // ?man -3: specify option flag + // ?man -3: print the previous, current, and next month case '3': nmons = 3; if (--month == 0) { @@ -191,28 +191,28 @@ main(int argc, char *argv[]) year--; } break; - // ?man -c:num: print count or perform stdout action + // ?man -c:num: print num calendars in a row case 'c': ncols = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -f:num: force the operation + // ?man -f:num: use num as the first day of the week, where 0 is Sunday case 'f': fday = estrtonum(EARGF(usage()), 0, 6); break; - // ?man -m: specify mode or limit + // ?man -m: use Monday as the first day of the week case 'm': /* Monday */ fday = 1; break; - // ?man -n:num: print line numbers or counts + // ?man -n:num: output num months starting with the current month case 'n': nmons = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -s: silent mode or print summary + // ?man -s: use Sunday as the first day of the week case 's': /* Sunday */ fday = 0; break; #endif - // ?man -y: specify option flag + // ?man -y: print the entire year case 'y': month = 1; nmons = 12; diff --git a/cmd/posix/cat.c b/cmd/posix/cat.c @@ -15,8 +15,8 @@ usage(void) } // ?man cat: concatenate files and print to standard output -// ?man arguments: file ... -// ?man cat reads each file in sequence and writes it to standard output +// ?man arguments: [file ...] +// ?man cat reads each file in sequence and writes its contents to standard output // ?man if no file is given, or a file is -, standard input is read int main(int argc, char *argv[]) @@ -24,9 +24,8 @@ main(int argc, char *argv[]) int fd, ret = 0; ARGBEGIN { - // ?man -u: specify u option + // ?man -u: accepted for posix compatibility; output is always unbuffered case 'u': - // ?man -u: ignored; accepted for posix compatibility; output is always unbuffered break; default: usage(); diff --git a/cmd/posix/chgrp.c b/cmd/posix/chgrp.c @@ -48,7 +48,7 @@ main(int argc, char *argv[]) struct recursor r = { .fn = chgrp, .maxdepth = 1, .follow = 'P' }; ARGBEGIN { - // ?man -h: affect symbolic links instead of referenced files + // ?man -h: operate on symbolic links themselves instead of their targets case 'h': hflag = 1; break; @@ -56,11 +56,11 @@ main(int argc, char *argv[]) case 'R': r.maxdepth = 0; break; - // ?man -H: specify option flag + // ?man -H: dereference command-line symbolic links during recursive traversal case 'H': - // ?man -L: specify option flag + // ?man -L: dereference all symbolic links during recursive traversal case 'L': - // ?man -P: specify option flag + // ?man -P: preserve symbolic links during recursive traversal case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/chown.c b/cmd/posix/chown.c @@ -45,7 +45,8 @@ usage(void) } // ?man chown: change ownership -// ?man arguments: owner[:[group]] file ... +// ?man synopsis: owner[:[group]] file ... +// ?man synopsis: :group file ... // ?man change the user and group ownership of files and directories int main(int argc, char *argv[]) @@ -56,7 +57,7 @@ main(int argc, char *argv[]) char *owner, *group; ARGBEGIN { - // ?man -h: affect symbolic links instead of referenced files + // ?man -h: operate on symbolic links themselves instead of their targets case 'h': hflag = 1; break; @@ -66,11 +67,11 @@ main(int argc, char *argv[]) case 'R': r.maxdepth = 0; break; - // ?man -H: specify option flag + // ?man -H: dereference command-line symbolic links during recursive traversal case 'H': - // ?man -L: specify option flag + // ?man -L: dereference all symbolic links during recursive traversal case 'L': - // ?man -P: specify option flag + // ?man -P: preserve symbolic links during recursive traversal case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/cmp.c b/cmd/posix/cmp.c @@ -24,11 +24,11 @@ main(int argc, char *argv[]) int ret = 0, lflag = 0, sflag = 0, same = 1, b[2]; ARGBEGIN { - // ?man -l: list in long format + // ?man -l: print the byte number and differing bytes for every difference case 'l': lflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: print nothing and return status only case 's': sflag = 1; break; diff --git a/cmd/posix/comm.c b/cmd/posix/comm.c @@ -44,11 +44,11 @@ main(int argc, char *argv[]) int ret = 0, i, diff = 0, seenline = 0; ARGBEGIN { - // ?man -1: specify option flag + // ?man -1: suppress lines unique to file1 case '1': - // ?man -2: specify option flag + // ?man -2: suppress lines unique to file2 case '2': - // ?man -3: specify option flag + // ?man -3: suppress lines common to both files case '3': show &= 0x07 ^ (1 << (ARGC() - '1')); break; diff --git a/cmd/posix/cp.c b/cmd/posix/cp.c @@ -25,7 +25,7 @@ main(int argc, char *argv[]) case 'i': cp_iflag = 1; break; - // ?man -a: archive mode; equivalent to -dpR + // ?man -a: preserve devices, sockets, and fifos; implies -pPR case 'a': cp_follow = 'P'; cp_aflag = cp_pflag = cp_rflag = 1; @@ -34,7 +34,7 @@ main(int argc, char *argv[]) case 'f': cp_fflag = 1; break; - // ?man -p: preserve file attributes + // ?man -p: preserve mode, timestamps, and ownership case 'p': cp_pflag = 1; break; @@ -44,15 +44,15 @@ main(int argc, char *argv[]) case 'R': cp_rflag = 1; break; - // ?man -v: verbose mode; show progress + // ?man -v: write each copied source and destination path case 'v': cp_vflag = 1; break; - // ?man -H: specify option flag + // ?man -H: dereference source arguments that are symbolic links case 'H': - // ?man -L: specify option flag + // ?man -L: dereference all symbolic links case 'L': - // ?man -P: specify option flag + // ?man -P: preserve symbolic links case 'P': cp_follow = ARGC(); break; diff --git a/cmd/posix/cut.c b/cmd/posix/cut.c @@ -161,9 +161,20 @@ usage(void) argv0, argv0, argv0); } -// ?man cut: cut out fields from lines -// ?man arguments: -b list [file ... -// ?man print selected parts of lines from files +// ?man cut: extract columns of data +// ?man synopsis: -b list [-n] [file ...] +// ?man synopsis: -c list [file ...] +// ?man synopsis: -f list [-d delim] [-s] [file ...] +// ?man cut out bytes, characters or delimited fields from each line of file and +// ?man write to stdout. +// ?man If no file is given or file is '-', cut reads from stdin. +// ?man list is a comma or space separated list of numbers and ranges starting +// ?man from 1. +// ?man Ranges have the form 'N-M'. If N or M is missing, beginning or end +// ?man of line is assumed. +// ?man Numbers and ranges may be repeated, overlapping and in any order. +// ?man Selected input is written in the same order it is read +// ?man and is written exactly once. int main(int argc, char *argv[]) { @@ -171,27 +182,30 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b:list: list specifies byte | character positions. case 'b': - // ?man -c: print count or perform stdout action + // ?man -c:list: list specifies byte | character positions. case 'c': - // ?man -f:mode: force the operation + // ?man -f:list: list specifies field numbers. + // ?man Lines not containing field delimiters are passed through, unless -s is specified. case 'f': mode = ARGC(); parselist(EARGF(usage())); break; - // ?man -d:str: specify directory + // ?man -d:delim: Use delim as field delimiter, which can be an arbitrary string. + // ?man Default is '\\t'. case 'd': delim = EARGF(usage()); if (!*delim) eprintf("empty delimiter\n"); delimlen = unescape(delim); break; - // ?man -n: print line numbers or counts + // ?man -n: Do not split multibyte characters. + // ?man A character is written when its last byte is selected. case 'n': nflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: Suppress lines not containing field delimiters. case 's': sflag = 1; break; diff --git a/cmd/posix/date.c b/cmd/posix/date.c @@ -64,7 +64,8 @@ setdate(const char *s, struct tm *now) } // ?man date: print or set system date and time -// ?man arguments: +format | mmddHHMM[[CC]yy +// ?man synopsis: [-u] [-d time] [+format] +// ?man synopsis: [-u] [-d time] [mmddHHMM[[CC]yy]] // ?man display or configure the system date and time int main(int argc, char *argv[]) @@ -78,11 +79,11 @@ main(int argc, char *argv[]) eprintf("time:"); ARGBEGIN { - // ?man -d:num: specify directory + // ?man -d:time: print time as seconds since the Unix epoch case 'd': t = estrtonum(EARGF(usage()), 0, LLONG_MAX); break; - // ?man -u: unbuffered output + // ?man -u: print or set UTC time instead of local time case 'u': if (setenv("TZ", "UTC0", 1) < 0) eprintf("setenv:"); diff --git a/cmd/posix/df.c b/cmd/posix/df.c @@ -91,8 +91,8 @@ usage(void) eprintf("usage: %s [-a]\n", argv0); } -// ?man df: report disk space usage -// ?man display free and used disk space on filesystems +// ?man df: show file system usage +// ?man df displays the amount of disk space available on a file system. If no arguments are given, df shows all the file systems using 512-byte blocks. int main(int argc, char *argv[]) { @@ -101,24 +101,24 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: Show all file systems including dummy ones. This is the default option. case 'a': aflag = 1; break; - // ?man -h: suppress headers or print help + // ?man -h: Not implemented. case 'h': hflag = 1; kflag = 0; break; - // ?man -k: specify option flag + // ?man -k: Print sizes in 1024-byte blocks. case 'k': kflag = 1; hflag = 0; blksize = 1024; break; - // ?man -s: silent mode or print summary + // ?man -s: Accepted for compatibility; not implemented. case 's': - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: Not implemented. case 'i': eprintf("not implemented\n"); break; diff --git a/cmd/posix/du.c b/cmd/posix/du.c @@ -122,36 +122,36 @@ main(int argc, char *argv[]) char *bsize; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: display an entry for each file in the hierarchy case 'a': aflag = 1; break; - // ?man -d:num: specify directory + // ?man -d:depth: limit output to depth levels of subdirectories case 'd': dflag = 1; maxdepth = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -h: suppress headers or print help + // ?man -h: print sizes in human-readable units case 'h': hflag = 1; break; - // ?man -k: specify option flag + // ?man -k: report sizes in kilobytes instead of 512-byte blocks case 'k': kflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: display only the total for each specified file case 's': sflag = 1; break; - // ?man -x: hex format or match whole lines + // ?man -x: stay on the current file system case 'x': r.flags |= SAMEDEV; break; - // ?man -H: specify option flag + // ?man -H: follow symbolic links given on the command line case 'H': - // ?man -L: specify option flag + // ?man -L: follow all symbolic links case 'L': - // ?man -P: specify option flag + // ?man -P: do not follow symbolic links case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/env.c b/cmd/posix/env.c @@ -18,7 +18,7 @@ usage(void) } // ?man env: run command in modified environment -// ?man arguments: ... [var=value] ... [cmd [arg ... +// ?man arguments: [name=value ...] [cmd [arg ...]] // ?man set environment variables and run a command int main(int argc, char *argv[]) @@ -26,11 +26,11 @@ main(int argc, char *argv[]) int savederrno; ARGBEGIN { - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: ignore the inherited environment and start from an empty one case 'i': *environ = NULL; break; - // ?man -u:str: unbuffered output + // ?man -u:name: remove name from the environment case 'u': if (unsetenv(EARGF(usage())) < 0) eprintf("unsetenv:"); diff --git a/cmd/posix/expand.c b/cmd/posix/expand.c @@ -98,11 +98,11 @@ main(int argc, char *argv[]) char *tl = "8"; ARGBEGIN { - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: only expand tabs at the start of lines case 'i': iflag = 1; break; - // ?man -t:str: sort or specify timestamp + // ?man -t:list: use list as the tab size or tab stops case 't': tl = EARGF(usage()); if (!*tl) diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -1421,7 +1421,7 @@ usage(void) } // ?man find: search for files -// ?man arguments: path ... [expression ... +// ?man arguments: path ... [expression ...] // ?man search for files in a directory hierarchy int main(int argc, char **argv) @@ -1434,12 +1434,12 @@ main(int argc, char **argv) gflags.mindepth = -1; ARGBEGIN { - // ?man -H: specify option flag + // ?man -H: dereference symbolic links given on the command line case 'H': gflags.h = 1; gflags.l = 0; break; - // ?man -L: specify option flag + // ?man -L: dereference all symbolic links encountered case 'L': gflags.l = 1; gflags.h = 0; diff --git a/cmd/posix/fold.c b/cmd/posix/fold.c @@ -85,7 +85,7 @@ usage(void) } // ?man fold: wrap lines to fit width -// ?man arguments: FILE ... +// ?man arguments: file ... // ?man wrap input lines to fit a specified width int main(int argc, char *argv[]) @@ -94,19 +94,19 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: count bytes rather than characters case 'b': bflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: break at the last space within the width when possible case 's': sflag = 1; break; - // ?man -w:num: wait for completion + // ?man -w:num: wrap lines at num columns instead of 80 case 'w': width = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man ARGNUM: specify RGNUM option + /* -num is accepted as shorthand for -w num */ ARGNUM: if (!(width = ARGNUMF())) eprintf("illegal width value, too small\n"); diff --git a/cmd/posix/getconf.c b/cmd/posix/getconf.c @@ -23,7 +23,7 @@ usage(void) } // ?man getconf: query configuration variables -// ?man arguments: var [path +// ?man arguments: var [path] // ?man query system configuration variables int main(int argc, char *argv[]) @@ -34,7 +34,7 @@ main(int argc, char *argv[]) char *str; ARGBEGIN { - // ?man -v:str: verbose mode; show progress + // ?man -v:spec: accepted for compatibility; ignored case 'v': /* ignore */ EARGF(usage()); diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c @@ -244,7 +244,7 @@ usage(void) } // ?man grep: search files for a pattern -// ?man arguments: pattern] [file ... +// ?man arguments: pattern [file ...] // ?man grep searches the named input files for lines matching the given pattern // ?man if no files are named, or a file is -, standard input is searched // ?man by default, matching lines are written to standard output @@ -260,54 +260,54 @@ main(int argc, char *argv[]) ARGBEGIN { #if FEATURE_GREP_CONTEXT - // ?man -A:num: specify A option + // ?man -A:num: print num lines of trailing context after each match case 'A': // ?man -A num: print num lines of trailing context after each match Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -B:num: specify B option + // ?man -B:num: print num lines of leading context before each match case 'B': // ?man -B num: print num lines of leading context before each match Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -C:num: specify C option + // ?man -C:num: print num lines of context before and after each match case 'C': // ?man -C num: print num lines of context before and after each match; equivalent to -A num -B num Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man ARGNUM: specify RGNUM option + /* -num is accepted as shorthand for -C num */ ARGNUM: Aflag = Bflag = ARGNUMF(); break; #endif #if FEATURE_GREP_MAX_COUNT - // ?man -m:num: specify m option + // ?man -m:num: stop reading a file after num matching lines case 'm': // ?man -m num: stop reading a file after num matching lines mval = estrtonum(EARGF(usage()), 0, LONG_MAX); break; #endif - // ?man -E: specify E option + // ?man -E: interpret pattern as an extended regular expression case 'E': // ?man -E: interpret pattern as an extended regular expression Eflag = 1; Fflag = 0; flags |= REG_EXTENDED; break; - // ?man -F: specify F option + // ?man -F: interpret patterns as fixed strings case 'F': // ?man -F: interpret pattern as a list of fixed strings separated by newlines Fflag = 1; Eflag = 0; flags &= ~REG_EXTENDED; break; - // ?man -H: specify H option + // ?man -H: always print file names with matching lines case 'H': // ?man -H: always print the file name with matching lines Hflag = 1; hflag = 0; break; - // ?man -e:file: specify e option + // ?man -e:pattern: specify a pattern to match; may be given multiple times case 'e': // ?man -e pattern: specify a pattern to match; may be given multiple times arg = EARGF(usage()); @@ -317,7 +317,7 @@ main(int argc, char *argv[]) efshut(fp, arg); eflag = 1; break; - // ?man -f:file: specify f option + // ?man -f:file: read patterns from file, one per line case 'f': // ?man -f file: read patterns from file, one per line arg = EARGF(usage()); @@ -328,51 +328,51 @@ main(int argc, char *argv[]) efshut(fp, arg); fflag = 1; break; - // ?man -h: specify h option + // ?man -h: never print file names with matching lines case 'h': // ?man -h: never print file names with matching lines hflag = 1; Hflag = 0; break; - // ?man -c: specify c option + // ?man -c: print only a count of matching lines per file case 'c': // ?man -c: print only a count of matching lines per file /* FALLTHROUGH */ - // ?man -l: specify l option + // ?man -l: print only the names of files with at least one match case 'l': // ?man -l: print only the names of files with at least one matching line /* FALLTHROUGH */ - // ?man -n: specify n option + // ?man -n: prefix each matching line with its line number case 'n': // ?man -n: prefix each matching line with its line number within its file /* FALLTHROUGH */ - // ?man -q: specify q option + // ?man -q: print nothing and return success on the first match case 'q': // ?man -q: quiet mode; exit immediately with status 0 on first match and write nothing mode = ARGC(); break; - // ?man -i: specify i option + // ?man -i: perform case-insensitive matching case 'i': // ?man -i: perform case-insensitive matching flags |= REG_ICASE; iflag = 1; break; - // ?man -s: specify s option + // ?man -s: suppress errors for nonexistent or unreadable files case 's': // ?man -s: suppress error messages about nonexistent or unreadable files sflag = 1; break; - // ?man -v: specify v option + // ?man -v: select lines that do not match case 'v': // ?man -v: invert the sense of matching to select non-matching lines vflag = 1; break; - // ?man -w: specify w option + // ?man -w: match only whole words case 'w': // ?man -w: match only whole words wflag = 1; break; - // ?man -x: specify x option + // ?man -x: match only whole lines case 'x': // ?man -x: match only whole lines xflag = 1; diff --git a/cmd/posix/head.c b/cmd/posix/head.c @@ -41,11 +41,11 @@ main(int argc, char *argv[]) int ret = 0, newline = 0, many = 0; ARGBEGIN { - // ?man -n:num: print line numbers or counts + // ?man -n:num: display the first num lines of each file case 'n': n = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man ARGNUM: specify RGNUM option + /* -num is accepted as shorthand for -n num */ ARGNUM: n = ARGNUMF(); break; diff --git a/cmd/posix/id.c b/cmd/posix/id.c @@ -135,26 +135,26 @@ usage(void) eprintf("usage: %s [-n] [-g | -u | -G] [user | uid]\n", argv0); } -// ?man id: print user and group ids -// ?man arguments: user | uid -// ?man display real and effective user and group identities +// ?man id: print real and effective user and group ids +// ?man synopsis: [-n] [-g | -u | -G] [user | uid] +// ?man id prints user and group information of the calling process to standard output. If a login name or uid is specified, the user and group information of that user is displayed. int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -g: specify option flag + // ?man -g: Print only the effective group ID. case 'g': gflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: Print only the effective user ID. case 'u': uflag = 1; break; - // ?man -G: specify option flag + // ?man -G: Display group information as whitespace separated numbers, in no particular order. case 'G': Gflag = 1; break; - // ?man -n: print line numbers or counts + // ?man -n: Print names instead of ID numbers, for -g, -u, and -G. case 'n': nflag = 1; break; diff --git a/cmd/posix/join.c b/cmd/posix/join.c @@ -451,8 +451,17 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) } -// ?man join: join lines on common field -// ?man join lines of two sorted files on a common field +// ?man join: relational database operator +// ?man join lines from file1 and file2 on a matching field. +// ?man If one of the input files is '-', standard input is read for that file. +// ?man Files are read sequentially and are assumed to be sorted on the join +// ?man field. +// ?man join does not check the order of input, and joining two unsorted files will +// ?man produce unexpected output. +// ?man By default, input lines are matched on the first blank-separated +// ?man field; output lines are space-separated and consist of the join field +// ?man followed by the remaining fields from file1, +// ?man then the remaining fields from file2. int main(int argc, char *argv[]) { @@ -462,15 +471,15 @@ main(int argc, char *argv[]) char *fno; ARGBEGIN { - // ?man -1:num: specify option flag + // ?man -1:field: Join on the fieldth field of file 1. case '1': jf[0] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -2:num: specify option flag + // ?man -2:field: Join on the fieldth field of file 2. case '2': jf[1] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -a:str: print or show all entries + // ?man -a:fileno: Print unpairable lines from file fileno in addition to normal output. case 'a': fno = EARGF(usage()); if (strcmp(fno, "1") == 0) @@ -480,21 +489,29 @@ main(int argc, char *argv[]) else usage(); break; - // ?man -e:str: specify expression or pattern + // ?man -e:string: When used with -o, replace empty fields in the output list with string. case 'e': replace = EARGF(usage()); break; - // ?man -o:str: specify output file + // ?man -o:list: Format output according to the string list. + // ?man Each element of list may be either fileno.field or 0 representing the join field. + // ?man Elements in list may be separated by blanks or commas. + // ?man For example, + // ?man join -o "0 2.1 1.3" + // ?man would print the join field, the first field of file2, + // ?man then the third field of file1. + // ?man Only paired lines are formatted with the -o option. + // ?man Unpairable lines selected with -a or -v are printed raw. case 'o': oflag = 1; initolist(&output); makeolist(&output, EARGF(usage())); break; - // ?man -t:str: sort or specify timestamp + // ?man -t:delim: Use the arbitrary string delim as field delimiter for both input and output. case 't': sep = EARGF(usage()); break; - // ?man -v:str: verbose mode; show progress + // ?man -v:fileno: Print unpairable lines from file fileno instead of normal output. case 'v': pairs = 0; fno = EARGF(usage()); diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c @@ -19,7 +19,7 @@ usage(void) } // ?man ln: make links between files -// ?man arguments: target [name +// ?man arguments: target [name] // ?man create hard or symbolic links between files int main(int argc, char *argv[]) @@ -34,11 +34,11 @@ main(int argc, char *argv[]) case 'f': fflag = 1; break; - // ?man -L: specify option flag + // ?man -L: hard-link the target of a symbolic link rather than the link itself case 'L': flags |= AT_SYMLINK_FOLLOW; break; - // ?man -P: specify option flag + // ?man -P: hard-link a symbolic link itself rather than its target case 'P': flags &= ~AT_SYMLINK_FOLLOW; break; diff --git a/cmd/posix/logger.c b/cmd/posix/logger.c @@ -56,19 +56,19 @@ main(int argc, char *argv[]) char *buf = NULL, *tag = NULL; ARGBEGIN { - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: include the logger process ID with each message case 'i': logflags |= LOG_PID; break; - // ?man -p:str: preserve file attributes + // ?man -p:priority: log with the given facility.level priority case 'p': priority = decodepri(EARGF(usage())); break; - // ?man -s: silent mode or print summary + // ?man -s: also write each message to standard error case 's': logflags |= LOG_PERROR; break; - // ?man -t:str: sort or specify timestamp + // ?man -t:tag: add tag to each logged message case 't': tag = EARGF(usage()); break; diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c @@ -406,11 +406,11 @@ entcmp(const void *va, const void *vb) const struct entry *a = va, *b = vb; switch (sort) { - // ?man -S: sort by file size + // ?man -S: sort files by size in decreasing order case 'S': cmp = b->size - a->size; break; - // ?man -t: sort by modification time + // ?man -t: sort files by modification time case 't': if (!(cmp = b->t.tv_sec - a->t.tv_sec)) cmp = b->t.tv_nsec - a->t.tv_nsec; @@ -552,7 +552,7 @@ usage(void) } // ?man ls: list directory contents -// ?man arguments: [file ... +// ?man arguments: [file ...] // ?man list information about files and directories int main(int argc, char *argv[]) @@ -706,7 +706,7 @@ main(int argc, char *argv[]) uflag = 1; cflag = 0; break; - // ?man --: specify - option + /* --color[=when] is accepted as a long-option extension */ case '-': #if FEATURE_LS_COLOR // ?man --color [when]: control coloring diff --git a/cmd/posix/mesg.c b/cmd/posix/mesg.c @@ -17,7 +17,7 @@ usage(void) } // ?man mesg: control write access -// ?man arguments: n|y +// ?man synopsis: [n | y] // ?man allow or disallow other users to write to the terminal int main(int argc, char *argv[]) diff --git a/cmd/posix/mkfifo.c b/cmd/posix/mkfifo.c @@ -23,7 +23,7 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -m:mode: specify mode or limit + // ?man -m:mode: set the file mode of newly created named pipes case 'm': mode = parsemode(EARGF(usage()), mode, umask(0)); break; diff --git a/cmd/posix/nice.c b/cmd/posix/nice.c @@ -24,7 +24,7 @@ usage(void) } // ?man nice: run command with modified priority -// ?man arguments: cmd [arg ... +// ?man arguments: cmd [arg ...] // ?man run a command with modified scheduling priority int main(int argc, char *argv[]) @@ -32,7 +32,7 @@ main(int argc, char *argv[]) int val = 10, r, savederrno; ARGBEGIN { - // ?man -n:num: print line numbers or counts + // ?man -n:num: change niceness by num case 'n': val = estrtonum(EARGF(usage()), PRIO_MIN, PRIO_MAX); break; diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c @@ -73,7 +73,7 @@ nl(const char *fname, FILE *fp) if (line.data[0] != '\n') donumber = 1; break; - // ?man -p: preserve file attributes + /* pexpr line-matching mode */ case 'p': if (!regexec(preg + section, line.data, 0, NULL, 0)) donumber = 1; @@ -118,8 +118,20 @@ getlinetype(char *type, regex_t *preg) return type[0]; } -// ?man nl: number lines -// ?man number the lines of files +// ?man nl: line numbering filter +// ?man nl reads lines from file and writes them to stdout, numbering non-empty lines. +// ?man If no file is given nl reads from stdin. +// ?man nl treats the input text as a collection of logical pages divided into +// ?man logical page sections. +// ?man Each logical page consists of a header section, a body +// ?man section and a footer section. +// ?man Sections may be empty. +// ?man The start of each section is indicated by a single delimiting line, one of: +// ?man ::: header +// ?man :: body +// ?man : footer +// ?man If the input text contains no delimiting line then all of the input text +// ?man belongs to a single logical page body section. int main(int argc, char *argv[]) { @@ -129,7 +141,9 @@ main(int argc, char *argv[]) char *d, *formattype, *formatblit; ARGBEGIN { - // ?man -d:str: specify directory + // ?man -d:delim: Set delim as the delimiter for logical pages. + // ?man If delim is only one character, nl appends \":\" to it. + // ?man The default is \"\\:\". case 'd': switch (utflen((d = EARGF(usage())))) { case 0: @@ -148,27 +162,47 @@ main(int argc, char *argv[]) break; } break; - // ?man -f:str: force the operation + // ?man -f:type: Define which lines to number in the head | body | footer section: + // ?man a All lines. + // ?man n No lines. + // ?man t Only non-empty lines. + // ?man This is the default. + // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . case 'f': type[0] = getlinetype(EARGF(usage()), preg); break; - // ?man -b:str: specify block size or base directory + // ?man -b:type: Define which lines to number in the head | body | footer section: + // ?man a All lines. + // ?man n No lines. + // ?man t Only non-empty lines. + // ?man This is the default. + // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . case 'b': type[1] = getlinetype(EARGF(usage()), preg + 1); break; - // ?man -h:str: suppress headers or print help + // ?man -h:type: Define which lines to number in the head | body | footer section: + // ?man a All lines. + // ?man n No lines. + // ?man t Only non-empty lines. + // ?man This is the default. + // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . case 'h': type[2] = getlinetype(EARGF(usage()), preg + 2); break; - // ?man -i:num: interactive mode or prompt for confirmation + // ?man -i:num: Set the increment between numbered lines to num . case 'i': incr = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -l:num: list in long format + // ?man -l:num: Set the number of adjacent blank lines to be considered as one to num . + // ?man The default is 1. case 'l': blines = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -n:str: print line numbers or counts + // ?man -n:format: Set the line number output format to one of: + // ?man ln Left justified. + // ?man rn Right justified. + // ?man This is the default. + // ?man rz Right justified with leading zeroes. case 'n': formattype = EARGF(usage()); estrlcpy(format, "%", sizeof(format)); @@ -186,20 +220,23 @@ main(int argc, char *argv[]) estrlcat(format, formatblit, sizeof(format)); estrlcat(format, "*ld", sizeof(format)); break; - // ?man -p: preserve file attributes + // ?man -p: Do not reset line number for logical pages. case 'p': pflag = 1; break; - // ?man -s:str: silent mode or print summary + // ?man -s:sep: Use sep to separate line numbers and lines. + // ?man The default is \"\\t\". case 's': sep = EARGF(usage()); seplen = unescape(sep); break; - // ?man -v:num: verbose mode; show progress + // ?man -v:num: Start counting lines from num . + // ?man The default is 1. case 'v': startnum = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -w:num: wait for completion + // ?man -w:num: Set the width of the line number to num . + // ?man The default is 6. case 'w': width = estrtonum(EARGF(usage()), 1, INT_MAX); break; diff --git a/cmd/posix/nohup.c b/cmd/posix/nohup.c @@ -17,7 +17,7 @@ usage(void) } // ?man nohup: run command immune to hangups -// ?man arguments: cmd [arg ... +// ?man arguments: cmd [arg ...] // ?man run a command that persists after logging out int main(int argc, char *argv[]) diff --git a/cmd/posix/od.c b/cmd/posix/od.c @@ -61,7 +61,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) }; switch (format) { - // ?man -a: print or show all entries + // equivalent to -t a case 'a': c = *s & ~128; /* clear high bit as required by standard */ if (c < LEN(namedict) || c == 127) { @@ -70,7 +70,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) printf(" %3c", c); } break; - // ?man -c: print count or perform stdout action + // equivalent to -t c case 'c': if (strchr("\a\b\t\n\v\f\r\0", *s)) { printf(" %3s", escdict[*s]); @@ -214,8 +214,9 @@ usage(void) "[-j skip] [-t outputformat] [file ...]\n", argv0); } -// ?man od: dump files in formats -// ?man display file contents in octal, hex, or other formats +// ?man od: octal dump +// ?man od writes an octal dump of each file to stdout. +// ?man If no file is given od reads from stdin. int main(int argc, char *argv[]) { @@ -226,65 +227,72 @@ main(int argc, char *argv[]) big_endian = (*(uint16_t *)"\0\xff" == 0xff); ARGBEGIN { - // ?man -A:str: specify option flag + // ?man -A:addressformat: addressformat is one of d|o|x|n and sets the address to be + // ?man either in decimal, octal, hexadecimal or not printed at all. + // ?man The default is octal. case 'A': s = EARGF(usage()); if (strlen(s) != 1 || !strchr("doxn", s[0])) usage(); addr_format = s[0]; break; - // ?man -b: specify block size or base directory + // ?man -b: Equivalent to -t o1 . case 'b': addtype('o', 1); break; - // ?man -d: specify directory + // ?man -d: Equivalent to -t u2 . case 'd': addtype('u', 2); break; #if FEATURE_OD_ENDIAN - // ?man -E: specify option flag + // ?man -E: Force Little Endian ( e ) or Big Endian ( E ) system-independently. case 'E': - // ?man -e: specify expression or pattern + // ?man -e: Force Little Endian ( e ) or Big Endian ( E ) system-independently. case 'e': big_endian = (ARGC() == 'E'); break; #endif - // ?man -j:str: specify option flag + // ?man -j:skip: Ignore the first skip bytes of input. case 'j': if ((skip = parseoffset(EARGF(usage()))) < 0) usage(); break; - // ?man -N:str: specify option flag + // ?man -N:num: read at most num bytes of input case 'N': if ((max = parseoffset(EARGF(usage()))) < 0) usage(); break; - // ?man -o: specify output file + // ?man -o: Equivalent to -t o2 . case 'o': addtype('o', 2); break; - // ?man -s: silent mode or print summary + // ?man -s: Equivalent to -t d2 . case 's': addtype('d', 2); break; - // ?man -t:str: sort or specify timestamp + // ?man -t:outputformat: outputformat is a list of a|c|d|o|u|x followed by a digit or C|S|I|L and sets + // ?man the content to be in named character, character, signed + // ?man decimal, octal, unsigned decimal, or + // ?man hexadecimal format, processing the given amount of bytes or the length + // ?man of Char, Short, Integer or Long. + // ?man The default is octal with 4 bytes. case 't': s = EARGF(usage()); for (; *s; s++) { switch (*s) { - // ?man -a: print or show all entries + /* outputformat a is equivalent to -t a */ case 'a': - // ?man -c: print count or perform stdout action + /* outputformat c is equivalent to -t c */ case 'c': addtype(*s, 1); break; - // ?man -d: specify directory + /* outputformat d is equivalent to -t d */ case 'd': - // ?man -o: specify output file + /* outputformat o is equivalent to -t o */ case 'o': - // ?man -u: unbuffered output + /* outputformat u is equivalent to -t u */ case 'u': - // ?man -x: hex format or match whole lines + /* outputformat x is equivalent to -t x */ case 'x': fmt_char = *s; if (isdigit((unsigned char)*(s + 1))) { @@ -292,22 +300,22 @@ main(int argc, char *argv[]) s = end - 1; } else { switch (*(s + 1)) { - // ?man -C: specify option flag + /* outputformat C uses sizeof(char) bytes */ case 'C': len = sizeof(char); s++; break; - // ?man -S: specify option flag + /* outputformat S uses sizeof(short) bytes */ case 'S': len = sizeof(short); s++; break; - // ?man -I: specify option flag + /* outputformat I uses sizeof(int) bytes */ case 'I': len = sizeof(int); s++; break; - // ?man -L: specify option flag + /* outputformat L uses sizeof(long) bytes */ case 'L': len = sizeof(long); s++; @@ -323,11 +331,12 @@ main(int argc, char *argv[]) } } break; - // ?man -v: verbose mode; show progress + // ?man -v: Always set. + // ?man Write all input data, including duplicate lines. case 'v': /* always set, use uniq(1) to handle duplicate lines */ break; - // ?man -x: hex format or match whole lines + // ?man -x: Equivalent to -t x2 . case 'x': addtype('x', 2); break; diff --git a/cmd/posix/paste.c b/cmd/posix/paste.c @@ -99,11 +99,11 @@ main(int argc, char *argv[]) char *delim = "\t"; ARGBEGIN { - // ?man -s: silent mode or print summary + // ?man -s: read each file sequentially instead of in parallel case 's': seq = 1; break; - // ?man -d:str: specify directory + // ?man -d:list: replace newlines using escaped characters from list case 'd': delim = EARGF(usage()); delim_bytelen = unescape(delim); diff --git a/cmd/posix/pathchk.c b/cmd/posix/pathchk.c @@ -89,11 +89,11 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -p: preserve file attributes + // ?man -p: check pathnames for portability across POSIX systems case 'p': most = 1; break; - // ?man -P: specify option flag + // ?man -P: also reject empty pathnames and leading hyphens case 'P': extra = 1; break; diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c @@ -846,11 +846,9 @@ readpax(struct bufio *f, struct header *h) case 'g': readexthdr(f, &globexthdr, h->size); break; - // ?man -x: hex format or match whole lines case 'x': readexthdr(f, &exthdr, h->size); break; - // ?man -L: specify option flag case 'L': if ((exthdr.delete | opt.delete) & PATH) break; @@ -2084,9 +2082,7 @@ parsereplstr(char *str) for (;;) { switch (*++str) { case 'g': r->global = 1; break; - // ?man -p: preserve file attributes case 'p': r->print = 1; break; - // ?man -s: silent mode or print summary case 's': r->symlink = 0; break; case 'S': r->symlink = 1; break; case 0: goto done; @@ -2333,6 +2329,10 @@ handle_append(const char *filename, const char *algo, const char *format) } // ?man pax: portable archive interchange +// ?man synopsis: [-cdiknuvX] [-f archive] [-o options] [-p string] [-s replstr] [pattern ...] +// ?man synopsis: -r [-cdiknuvX] [-f archive] [-o options] [-p string] [-s replstr] [pattern ...] +// ?man synopsis: -w [-adituvX] [-b blocksize] [-f archive] [-o options] [-x format] [-j | -J | -z] [file ...] +// ?man synopsis: -rw [-diklntuvX] [-H | -L] [-p string] [-s replstr] [file ...] directory // ?man read, write, and list member files of archive files int main(int argc, char *argv[]) @@ -2349,113 +2349,108 @@ main(int argc, char *argv[]) size_t l; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: append files to the end of an existing archive case 'a': aflag = 1; break; - // ?man -b:str: specify block size or base directory + // ?man -b:blocksize: accepted for compatibility; block size is currently ignored case 'b': EARGF(usage()); break; - // ?man -c: print count or perform stdout action + // ?man -c: invert the sense of path matching case 'c': cflag = 1; break; - // ?man -d: specify directory + // ?man -d: do not match pathnames of directory entries against patterns case 'd': dflag = 1; break; - // ?man -f:str: force the operation + // ?man -f:archive: read from or write to archive instead of standard input or output case 'f': name = EARGF(usage()); break; - // ?man -H: specify option flag + // ?man -H: follow symbolic links named on the command line case 'H': follow = 'H'; break; - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: rename or skip files interactively case 'i': iflag = 1; break; - // ?man -j: specify option flag + // ?man -j: compress or decompress the archive with bzip2 case 'j': algo = "bzip2"; break; - // ?man -J: specify option flag + // ?man -J: compress or decompress the archive with xz case 'J': algo = "xz"; break; - // ?man -k: specify option flag + // ?man -k: do not overwrite existing files case 'k': kflag = 1; break; - // ?man -l: list in long format + // ?man -l: link files instead of copying them during pass mode when possible case 'l': lflag = 1; break; - // ?man -L: specify option flag + // ?man -L: follow all symbolic links case 'L': follow = 'L'; break; - // ?man -n: print line numbers or counts + // ?man -n: use only the first archive member that matches each pattern case 'n': nflag = 1; break; - // ?man -o:str: specify output file + // ?man -o:options: set format-specific archive options case 'o': parseopts(EARGF(usage())); break; - // ?man -p:str: preserve file attributes + // ?man -p:string: control which file attributes are preserved in pass mode case 'p': for (arg = EARGF(usage()); *arg; ++arg) { switch (*arg) { - // ?man -a: print or show all entries case 'a': preserve &= ~ATIME; break; - // ?man -e: specify expression or pattern case 'e': preserve = ~0; break; - // ?man -m: specify mode or limit case 'm': preserve &= ~MTIME; break; - // ?man -o: specify output file case 'o': preserve |= UID | GID; break; - // ?man -p: preserve file attributes case 'p': preserve |= MODE; break; default: fatal("unknown -p option"); } } break; - // ?man -r: operate recursively + // ?man -r: read an archive and extract matching members case 'r': mode |= READ; break; - // ?man -s:str: silent mode or print summary + // ?man -s:replstr: rename archive members or files using a substitution expression case 's': parsereplstr(EARGF(usage())); break; - // ?man -t: sort or specify timestamp + // ?man -t: preserve access times of files read by pax case 't': tflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: copy or extract only files newer than existing destination files case 'u': uflag = 1; break; - // ?man -v: verbose mode; show progress + // ?man -v: write verbose filenames while processing files case 'v': vflag = 1; break; - // ?man -w: wait for completion + // ?man -w: write an archive or enter pass mode case 'w': mode |= WRITE; break; - // ?man -x:str: hex format or match whole lines + // ?man -x:format: use the archive format format case 'x': format = EARGF(usage()); break; - // ?man -X: specify option flag + // ?man -X: stay on the current file system when descending directories case 'X': Xflag = 1; break; - // ?man -z: specify option flag + // ?man -z: compress or decompress the archive with gzip case 'z': algo = "gzip"; break; diff --git a/cmd/posix/printf.c b/cmd/posix/printf.c @@ -75,7 +75,7 @@ usage(void) } // ?man printf: format and print data -// ?man arguments: format [arg ... +// ?man arguments: format [arg ...] // ?man format and print arguments to standard output int main(int argc, char *argv[]) diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c @@ -150,29 +150,29 @@ usage(void) eprintf("usage: %s [-aAdef]\n", argv0); } -// ?man ps: report process status -// ?man display information about active system processes +// ?man ps: display process status +// ?man ps displays information about active processes. When given no options, ps prints information about processes of the current user that has a controlling terminal. int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: Select all processes except both session leaders and processes not associated with a terminal. case 'a': flags |= PS_aflag; break; - // ?man -A: specify option flag + // ?man -A: Select all processes. Identical to -e. case 'A': flags |= PS_Aflag; break; - // ?man -d: specify directory + // ?man -d: Select all processes except session leaders. case 'd': flags |= PS_dflag; break; - // ?man -e: specify expression or pattern + // ?man -e: Select all processes. Identical to -A. case 'e': flags |= PS_Aflag; break; - // ?man -f: force the operation + // ?man -f: Do full-format listing. case 'f': flags |= PS_fflag; break; diff --git a/cmd/posix/pwd.c b/cmd/posix/pwd.c @@ -38,9 +38,9 @@ main(int argc, char *argv[]) char mode = 'L'; ARGBEGIN { - // ?man -L: specify option flag + // ?man -L: print the logical path using PWD when possible case 'L': - // ?man -P: specify option flag + // ?man -P: print the physical path with all symbolic links resolved case 'P': mode = ARGC(); break; diff --git a/cmd/posix/readlink.c b/cmd/posix/readlink.c @@ -35,12 +35,12 @@ main(int argc, char *argv[]) ARGBEGIN { #if FEATURE_READLINK_REALPATH - // ?man -f: force the operation + // ?man -f: canonicalize path by following every symbolic link in its components case 'f': fflag = 1; break; #endif - // ?man -n: print line numbers or counts + // ?man -n: do not print the trailing newline case 'n': nflag = 1; break; diff --git a/cmd/posix/renice.c b/cmd/posix/renice.c @@ -55,19 +55,19 @@ main(int argc, char *argv[]) int who; ARGBEGIN { - // ?man -n:str: print line numbers or counts + // ?man -n:num: change niceness by num case 'n': adj = EARGF(usage()); break; - // ?man -g: specify option flag + // ?man -g: treat each id as a process group ID case 'g': which = PRIO_PGRP; break; - // ?man -p: preserve file attributes + // ?man -p: treat each id as a process ID case 'p': which = PRIO_PROCESS; break; - // ?man -u: unbuffered output + // ?man -u: treat each id as a user name or user ID case 'u': which = PRIO_USER; break; diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c @@ -1750,8 +1750,10 @@ old_next(void) } // ?man sed: stream editor -// ?man arguments: script [file ... -// ?man stream editor for filtering and transforming text +// ?man synopsis: [-nrE] script [file ...] +// ?man synopsis: [-nrE] -e script [-e script] ... [-f scriptfile] ... [file ...] +// ?man synopsis: [-nrE] [-e script] ... -f scriptfile [-f scriptfile] ... [file ...] +// ?man sed reads line oriented output from file or stdin, applies the editing commands supplied by script or scriptfile and writes the edited stream to stdout. int main(int argc, char *argv[]) { @@ -1759,30 +1761,30 @@ main(int argc, char *argv[]) int script = 0; ARGBEGIN { - // ?man -n: print line numbers or counts + // ?man -n: Suppress default printing at the end of each cycle. case 'n': gflags.n = 1; break; - // ?man -r: operate recursively + // ?man -r: Use extended regular expressions case 'r': - // ?man -E: specify option flag + // ?man -E: Use extended regular expressions case 'E': gflags.E = 1; break; - // ?man -e:str: specify expression or pattern + // ?man -e:script: Append script to the list of editing commands. case 'e': arg = EARGF(usage()); compile(arg, 0); script = 1; break; - // ?man -f:str: force the operation + // ?man -f:scriptfile: Append the commands from scriptfile to the list of editing commands. case 'f': arg = EARGF(usage()); compile(arg, 1); script = 1; break; #if FEATURE_SED_INPLACE - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: edit files in place case 'i': iflag = 1; if (argv[0][1] != '\0') { @@ -1796,6 +1798,77 @@ main(int argc, char *argv[]) default : usage(); } ARGEND + // ?man ## Extended description + // ?man Editing commands take the form + // ?man + // ?man `[address[,address]]function` + // ?man + // ?man ### Addresses + // ?man Addresses are either blank, a positive decimal integer denoting a line + // ?man number, the character '$' denoting the last line of input, or a regular + // ?man expression. + // ?man A command with no addresses matches every line, one address matches + // ?man individual lines, and two addresses matches a range of lines from the + // ?man first to the second address inclusive. + // ?man ### Functions + // ?man `a [text]` + // ?man : Append text to output after end of current cycle. + // ?man `b [label]` + // ?man : Branch to label. If no label is provided branch to end of script. + // ?man `c [text]` + // ?man : Change. Delete addressed range and output text after end of current cycle. + // ?man `d` + // ?man : Delete pattern space and begin next cycle. + // ?man `D` + // ?man : Delete pattern space up to and including first newline and begin new cycle without reading input. If there is no newline, behave like d. + // ?man `g` + // ?man : Get. Replace the pattern space with the hold space. + // ?man `G` + // ?man : Get. Append a newline and the hold space to the pattern space. + // ?man `h` + // ?man : Hold. Replace the hold space with the pattern space. + // ?man `H` + // ?man : Hold. Append a newline and the pattern space to the hold space. + // ?man `i [text]` + // ?man : Insert text in output. + // ?man `l` + // ?man : List? Write the pattern space replacing known non printing characters with backslash escaped versions (`\\\\`, `\\a`, `\\b`, `\\f`, `\\r`, `\\t`, `\\v`). Print bad UTF-8 sequences as `\\ooo` where ooo is a three digit octal number. Mark end of lines with '$'. + // ?man `n` + // ?man : Next. Write pattern space (unless `-n`), read next line into pattern space, and continue current cycle. If there is no next line, quit. + // ?man `N` + // ?man : Next. Read next line, append newline and next line to pattern space, and continue cycle. If there is no next line, quit without printing current pattern space. + // ?man `p` + // ?man : Print current pattern space. + // ?man `P` + // ?man : Print current pattern space up to first newline. + // ?man `q` + // ?man : Quit. + // ?man `r file` + // ?man : Read file and write contents to output. + // ?man `s/re/text/flags` + // ?man : Find occurences of regular expression re in the pattern space and replace with text. A '&' in text is replaced with the entire match. A `\\d` where d is a decimal digit 1-9 is replaced with the corresponding match group from the regular expression. `\\n` represents a newline in both the regular expression and replacement text. A literal newline in the replacement text must be preceded by a `\\`. + // ?man ### Flags + // ?man `n` + // ?man : A positive decimal number denoting which match in the pattern space to replace. + // ?man `g` + // ?man : Global. Replace all matches in the pattern space. + // ?man `p` + // ?man : Print the pattern if a replacement was made. + // ?man `w file` + // ?man : Write the pattern space to file if a replacement was made. + // ?man `t [label]` + // ?man : Test. Branch to corresponding label if a substitution has been made since the last line was read or last t command was executed. If no label is provided branch to end of script. + // ?man `w file` + // ?man : Write pattern space to file. + // ?man `x` + // ?man : Exchange hold space and pattern space. + // ?man `y/set1/set2/` + // ?man : Replace each occurrence of a character from set 1 with the corresponding character from set 2. + // ?man `:label` + // ?man : Create a label for b and t commands. + // ?man `=` + // ?man : Write current input line number to output. + /* no script to run */ if (!script && !argc) usage(); diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c @@ -305,27 +305,27 @@ parse_flags(char **s, int *flags, int bflag) { while (isalpha((int)**s)) { switch (*((*s)++)) { - // ?man -b: specify block size or base directory + /* parse key-specific b modifier */ case 'b': *flags |= bflag; break; - // ?man -d: specify directory + /* parse key-specific d modifier */ case 'd': *flags |= MOD_D; break; - // ?man -f: force the operation + /* parse key-specific f modifier */ case 'f': *flags |= MOD_F; break; - // ?man -i: interactive mode or prompt for confirmation + /* parse key-specific i modifier */ case 'i': *flags |= MOD_I; break; - // ?man -n: print line numbers or counts + /* parse key-specific n modifier */ case 'n': *flags |= MOD_N; break; - // ?man -r: operate recursively + /* parse key-specific r modifier */ case 'r': *flags |= MOD_R; break; @@ -396,8 +396,9 @@ usage(void) } // ?man sort: sort lines -// ?man arguments: -Cbcdfimnru -// ?man sort or merge lines of text files +// ?man synopsis: [-Cbcdfimnru] [-o outfile] [-t delim] [-k key ...] [file ...] +// ?man sort writes the sorted concatenation of each file to stdout. +// ?man If no file is given sort reads from stdin. int main(int argc, char *argv[]) { @@ -408,35 +409,44 @@ main(int argc, char *argv[]) char *outfile = NULL; ARGBEGIN { - // ?man -C: specify option flag + // ?man -C: Check that the concatenation of the given files is sorted rather than sorting them. + // ?man In this mode, no output is printed to stdout, and the exit status indicates the result of the check. case 'C': Cflag = 1; break; - // ?man -b: specify block size or base directory + // ?man -b: Skip leading whitespace of columns when sorting. case 'b': global_flags |= MOD_STARTB | MOD_ENDB; break; - // ?man -c: print count or perform stdout action + // ?man -c: The same as -C except that when disorder is detected, a message is written to stderr indicating the location of the disorder. case 'c': cflag = 1; break; - // ?man -d: specify directory + // ?man -d: Skip non-whitespace and non-alphanumeric characters. case 'd': global_flags |= MOD_D; break; - // ?man -f: force the operation + // ?man -f: Ignore letter case when sorting. case 'f': global_flags |= MOD_F; break; - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: Skip non-printable characters. case 'i': global_flags |= MOD_I; break; - // ?man -k:str: specify option flag + // ?man -k:key: Specify a key definition of the form S[.s][f][,E[.e][f]] where S, + // ?man s, E and e are the starting column, starting character in that column, + // ?man ending column and the ending character of that column respectively. + // ?man If they are not specified, s refers to the first character of the + // ?man specified starting column, E refers to the last column of every line, + // ?man and e refers to the last character of the ending column. + // ?man f can be used to specify options (n, b) that only apply to this key + // ?man definition. + // ?man b is special in that it only applies to the column that it was specified after. case 'k': addkeydef(EARGF(usage()), global_flags); break; - // ?man -m: specify mode or limit + // ?man -m: Assume sorted input, merge only. case 'm': /* more or less for free, but for performance-reasons, * we should keep this flag in mind and maybe some later @@ -444,37 +454,37 @@ main(int argc, char *argv[]) * while merging large sorted files. */ break; - // ?man -n: print line numbers or counts + // ?man -n: Perform a numeric sort. case 'n': global_flags |= MOD_N; break; - // ?man -o:file: specify output file + // ?man -o:outfile: Write output to outfile rather than stdout. case 'o': outfile = EARGF(usage()); break; - // ?man -r: operate recursively + // ?man -r: Reverses the sort. case 'r': global_flags |= MOD_R; break; #if FEATURE_SORT_STABLE - // ?man -s: silent mode or print summary + // ?man -s: stabilize the sort by preserving the input order of equal lines case 's': sflag = 1; break; #endif - // ?man -t:str: sort or specify timestamp + // ?man -t:delim: Set delim as the field delimiter. case 't': fieldsep = EARGF(usage()); if (!*fieldsep) eprintf("empty delimiter\n"); fieldseplen = unescape(fieldsep); break; - // ?man -u: unbuffered output + // ?man -u: Print equal lines only once. case 'u': uflag = 1; break; #if FEATURE_SORT_BIG - // ?man -z: specify option flag + // ?man -z: treat input as NUL-separated records case 'z': zflag = 1; break; diff --git a/cmd/posix/split.c b/cmd/posix/split.c @@ -47,7 +47,7 @@ usage(void) } // ?man split: split file into pieces -// ?man arguments: | -l num +// ?man arguments: [file] [prefix] // ?man split a file into fixed-size pieces int main(int argc, char *argv[]) @@ -58,11 +58,11 @@ main(int argc, char *argv[]) char name[NAME_MAX + 1], *prefix = "x", *file = NULL; ARGBEGIN { - // ?man -a:num: print or show all entries + // ?man -a:num: use num characters for generated filename suffixes case 'a': slen = estrtonum(EARGF(usage()), 0, INT_MAX); break; - // ?man -b:str: specify block size or base directory + // ?man -b:num: start a new file every num bytes case 'b': always = 1; if ((size = parseoffset(EARGF(usage()))) < 0) @@ -70,12 +70,12 @@ main(int argc, char *argv[]) if (!size) eprintf("size needs to be positive\n"); break; - // ?man -d: specify directory + // ?man -d: use decimal suffixes instead of alphabetic ones case 'd': base = 10; start = '0'; break; - // ?man -l:num: list in long format + // ?man -l:num: start a new file every num lines case 'l': always = 0; size = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SSIZE_MAX)); diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c @@ -168,15 +168,15 @@ main(int argc, char *argv[]) int (*tail)(int, const char *, size_t) = taketail; ARGBEGIN { - // ?man -f: force the operation + // ?man -f: continue writing appended data as the file grows case 'f': fflag = 1; break; - // ?man -c: print count or perform stdout action + // ?man -c:num: display the last num bytes of each file case 'c': - // ?man -m: specify mode or limit + // ?man -m:num: display the last num characters of each file case 'm': - // ?man -n:num: print line numbers or counts + // ?man -n:num: display the last num lines of each file case 'n': mode = ARGC(); numstr = EARGF(usage()); @@ -185,7 +185,7 @@ main(int argc, char *argv[]) if (strchr(numstr, '+')) tail = dropinit; break; - // ?man ARGNUM: specify RGNUM option + // ?man -num: display the last num lines of each file ARGNUM: n = ARGNUMF(); break; diff --git a/cmd/posix/tee.c b/cmd/posix/tee.c @@ -26,11 +26,11 @@ main(int argc, char *argv[]) char buf[BUFSIZ]; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: append to each file instead of overwriting it case 'a': aflag = O_APPEND; break; - // ?man -i: interactive mode or prompt for confirmation + // ?man -i: ignore SIGINT case 'i': iflag = 1; break; diff --git a/cmd/posix/time.c b/cmd/posix/time.c @@ -17,7 +17,7 @@ usage(void) } // ?man time: time command execution -// ?man arguments: cmd [arg ... +// ?man arguments: cmd [arg ...] // ?man run a command and report its execution duration int main(int argc, char *argv[]) @@ -29,7 +29,7 @@ main(int argc, char *argv[]) int status, savederrno, ret = 0; ARGBEGIN { - // ?man -p: preserve file attributes + // ?man -p: use the portable output format "real %f\\nuser %f\\nsys %f\\n" case 'p': break; default: diff --git a/cmd/posix/touch.c b/cmd/posix/touch.c @@ -116,26 +116,26 @@ main(int argc, char *argv[]) char *ref = NULL; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: change only the access time case 'a': aflag = 1; break; - // ?man -c: print count or perform stdout action + // ?man -c: do not create files that do not exist case 'c': cflag = 1; break; - // ?man -d: specify directory + // ?man -d: set the timestamp from a parsed date string case 'd': - // ?man -t:str: sort or specify timestamp + // ?man -t:time: set the timestamp from [[CC]YY]MMDDhhmm[.SS] case 't': times[0].tv_sec = parsetime(EARGF(usage())); times[0].tv_nsec = 0; break; - // ?man -m: specify mode or limit + // ?man -m: change only the modification time case 'm': mflag = 1; break; - // ?man -r:str: operate recursively + // ?man -r:ref_file: use the timestamps from ref_file case 'r': ref = EARGF(usage()); if (stat(ref, &st) < 0) @@ -143,7 +143,7 @@ main(int argc, char *argv[]) times[0] = st.st_atim; times[1] = st.st_mtim; break; - // ?man -T:num: specify option flag + // ?man -T:time: set the timestamp from seconds since the Unix epoch case 'T': times[0].tv_sec = estrtonum(EARGF(usage()), 0, LLONG_MAX); times[0].tv_nsec = 0; diff --git a/cmd/posix/tr.c b/cmd/posix/tr.c @@ -190,7 +190,7 @@ usage(void) } // ?man tr: translate characters -// ?man arguments: set1 [set2 +// ?man arguments: set1 [set2] // ?man translate, squeeze, or delete characters from standard input int main(int argc, char *argv[]) @@ -200,17 +200,17 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -c: print count or perform stdout action + // ?man -c: use the complement of set1 case 'c': - // ?man -C: specify option flag + // ?man -C: use the complement of set1 case 'C': cflag = 1; break; - // ?man -d: specify directory + // ?man -d: delete input characters that match set1 case 'd': dflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: squeeze repeated output characters that match set2, or set1 if -d is set case 's': sflag = 1; break; diff --git a/cmd/posix/uname.c b/cmd/posix/uname.c @@ -22,27 +22,27 @@ main(int argc, char *argv[]) int mflag = 0, nflag = 0, rflag = 0, sflag = 0, vflag = 0; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: print all available system information case 'a': mflag = nflag = rflag = sflag = vflag = 1; break; - // ?man -m: specify mode or limit + // ?man -m: print the machine hardware name case 'm': mflag = 1; break; - // ?man -n: print line numbers or counts + // ?man -n: print the network node hostname case 'n': nflag = 1; break; - // ?man -r: operate recursively + // ?man -r: print the operating system release case 'r': rflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: print the operating system name case 's': sflag = 1; break; - // ?man -v: verbose mode; show progress + // ?man -v: print the operating system version case 'v': vflag = 1; break; diff --git a/cmd/posix/unexpand.c b/cmd/posix/unexpand.c @@ -141,13 +141,13 @@ main(int argc, char *argv[]) char *tl = "8"; ARGBEGIN { - // ?man -t:str: sort or specify timestamp + // ?man -t:list: use list as the tab size or tab stops case 't': tl = EARGF(usage()); if (!*tl) eprintf("tablist cannot be empty\n"); /* fallthrough */ - // ?man -a: print or show all entries + // ?man -a: convert spaces to tabs throughout each line, not just leading blanks case 'a': aflag = 1; break; diff --git a/cmd/posix/uniq.c b/cmd/posix/uniq.c @@ -109,23 +109,23 @@ main(int argc, char *argv[]) char *fname[2] = { "<stdin>", "<stdout>" }; ARGBEGIN { - // ?man -c: print count or perform stdout action + // ?man -c: prefix each output line with its number of consecutive occurrences case 'c': countfmt = "%7ld "; break; - // ?man -d: specify directory + // ?man -d: print only duplicate lines case 'd': dflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: print only unique lines case 'u': uflag = 1; break; - // ?man -f:num: force the operation + // ?man -f:num: ignore the first num fields when comparing lines case 'f': fskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; - // ?man -s:num: silent mode or print summary + // ?man -s:num: ignore the first num characters when comparing lines case 's': sskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; diff --git a/cmd/posix/uuencode.c b/cmd/posix/uuencode.c @@ -99,7 +99,7 @@ usage(void) } // ?man uuencode: encode binary file -// ?man arguments: file] name +// ?man arguments: [file] name // ?man encode a binary file into ascii text int main(int argc, char *argv[]) diff --git a/cmd/posix/wc.c b/cmd/posix/wc.c @@ -79,19 +79,19 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -c: print count or perform stdout action + // ?man -c: print the number of bytes case 'c': cmode = 'c'; break; - // ?man -m: specify mode or limit + // ?man -m: print the number of characters case 'm': cmode = 'm'; break; - // ?man -l: list in long format + // ?man -l: print the number of lines case 'l': lflag = 1; break; - // ?man -w: wait for completion + // ?man -w: print the number of words case 'w': wflag = 1; break; diff --git a/cmd/posix/who.c b/cmd/posix/who.c @@ -17,8 +17,8 @@ usage(void) eprintf("usage: %s [-ml]\n", argv0); } -// ?man who: show logged in users -// ?man display a list of users currently logged into the system +// ?man who: print who has logged on +// ?man who prints a list of who has logged on, their controlling tty, and the time at which they logged on. int main(int argc, char *argv[]) { @@ -32,7 +32,7 @@ main(int argc, char *argv[]) time_t t; ARGBEGIN { - // ?man -m: specify mode or limit + // ?man -m: Only show users on current tty. case 'm': mflag = 1; tty = ttyname(0); @@ -41,7 +41,7 @@ main(int argc, char *argv[]) if ((ttmp = strrchr(tty, '/'))) tty = ttmp+1; break; - // ?man -l: list in long format + // ?man -l: Print LOGIN processes as well. case 'l': lflag = 1; break; diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c @@ -263,9 +263,21 @@ usage(void) argv0); } -// ?man xargs: build and run command lines -// ?man arguments: -n -// ?man execute commands built from standard input arguments +// ?man xargs: construct argument lists and execute command +// ?man synopsis: [-0prtx] [-E eofstr] [-I replstr] [-L maxlines] [-n num] [-P maxprocs] [-s num] [cmd [arg ...]] +// ?man xargs reads space, tab, newline and EOF delimited strings from stdin +// ?man and executes the specified cmd with the strings as arguments. +// ?man Any arguments specified on the command line are given to the command upon +// ?man each invocation, followed by some number of the arguments read from +// ?man stdin. +// ?man The command is repeatedly executed one or more times until stdin is exhausted. +// ?man Spaces, tabs and newlines may be embedded in arguments using single (`'') +// ?man or double (`"') quotes or backslashes ('\\'). +// ?man Single quotes escape all non-single quote characters, excluding newlines, up +// ?man to the matching single quote. +// ?man Double quotes escape all non-double quote characters, excluding newlines, up +// ?man to the matching double quote. +// ?man Any single character, including newlines, may be escaped by a backslash. int main(int argc, char *argv[]) { @@ -283,42 +295,45 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -0: specify option flag + // ?man -0: use NUL characters instead of blanks and newlines as argument separators case '0': nulflag = 1; break; - // ?man -n:num: print line numbers or counts + // ?man -n:num: Use at most num arguments per command line. case 'n': nflag = 1; maxargs = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -p: preserve file attributes + // ?man -p: prompt before running each constructed command line case 'p': pflag = 1; break; - // ?man -r: operate recursively + // ?man -r: Do not run the command if there are no arguments. + // ?man Normally the command is executed at least once even if there are no arguments. case 'r': rflag = 1; break; - // ?man -s:num: silent mode or print summary + // ?man -s:num: Use at most num bytes per command line. case 's': argmaxsz = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -t: sort or specify timestamp + // ?man -t: Write the command line to stderr before executing it. case 't': tflag = 1; break; - // ?man -x: hex format or match whole lines + // ?man -x: Terminate if the command line exceeds the system limit or the number of bytes given with the -s flag. case 'x': xflag = 1; break; - // ?man -E:str: specify option flag + // ?man -E:eofstr: Use eofstr as a logical EOF marker. case 'E': eofstr = EARGF(usage()); break; - // ?man -I:str: specify option flag + // ?man -I:replstr: Use replstr as the placeholder for the argument. + // ?man Sets the arguments count to 1 per command line. + // ?man It also implies the option x. case 'I': Iflag = 1; xflag = 1; @@ -326,13 +341,13 @@ main(int argc, char *argv[]) maxargs = 1; replstr = EARGF(usage()); break; - // ?man -L:num: specify option flag + // ?man -L:maxlines: use at most maxlines input lines per command line case 'L': Lflag = 1; maxlines = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -P:num: specify option flag + // ?man -P:maxprocs: run up to maxprocs commands at the same time case 'P': maxprocs = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c @@ -14,7 +14,7 @@ usage(void) } // ?man chroot: run command in new root -// ?man arguments: dir [cmd [arg ... +// ?man arguments: dir [cmd [arg ...]] // ?man run a command or shell with a substitute root directory int main(int argc, char *argv[]) diff --git a/cmd/pseudo/dmesg.c b/cmd/pseudo/dmesg.c @@ -31,8 +31,9 @@ usage(void) eprintf("usage: %s [-Ccr] [-n level]\n", argv0); } -// ?man dmesg: print kernel ring buffer -// ?man display or control the kernel ring buffer messages +// ?man dmesg: print or control the kernel ring buffer +// ?man dmesg examines or controls the kernel ring buffer. +// ?man By default it reads all the messages from the kernel ring buffer and prints them to stdout. int main(int argc, char *argv[]) { @@ -42,19 +43,20 @@ main(int argc, char *argv[]) long level; ARGBEGIN { - // ?man -C: specify option flag + // ?man -C: Clear the ring buffer. case 'C': if (clear_dmesg() < 0) eprintf("clear_dmesg:"); return 0; - // ?man -c: print count or perform stdout action + // ?man -c: Clear the ring buffer after printing its contents. case 'c': cflag = 1; break; - // ?man -r: operate recursively + // ?man -r: Print the raw message buffer. case 'r': break; - // ?man -n:num: print line numbers or counts + // ?man -n:level: Set the console level. + // ?man The log levels are defined in the file include/linux/kern_levels.h. case 'n': level = estrtol(EARGF(usage()), 10); if (set_console_level(level) < 0) @@ -88,4 +90,4 @@ main(int argc, char *argv[]) return 1; return 0; -} -\ No newline at end of file +} diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c @@ -18,7 +18,7 @@ usage(void) } // ?man flock: manage locks -// ?man arguments: file cmd [arg ... +// ?man arguments: file cmd [arg ...] // ?man acquire or release locks from shell scripts int main(int argc, char *argv[]) diff --git a/cmd/pseudo/free.c b/cmd/pseudo/free.c @@ -23,27 +23,27 @@ usage(void) eprintf("usage: %s [-bkmg]\n", argv0); } -// ?man free: display memory usage -// ?man display the amount of free and used memory in the system +// ?man free: display amount of free and used memory in the system +// ?man free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel. int main(int argc, char *argv[]) { struct MemInfo mi; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: Display the amount of memory in bytes. This is the default. case 'b': unit_shift = 0; break; - // ?man -k: specify option flag + // ?man -k: Display the amount of memory in kilobytes. case 'k': unit_shift = 10; break; - // ?man -m: specify mode or limit + // ?man -m: Display the amount of memory in megabytes. case 'm': unit_shift = 20; break; - // ?man -g: specify option flag + // ?man -g: Display the amount of memory in gigabytes. case 'g': unit_shift = 30; break; diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c @@ -27,7 +27,7 @@ usage(void) } // ?man getty: set terminal mode -// ?man arguments: tty] [term] [cmd] [args... +// ?man arguments: [tty] [term] [cmd] [args ...] // ?man set terminal line discipline, speed, and mode int main(int argc, char *argv[]) diff --git a/cmd/pseudo/login.c b/cmd/pseudo/login.c @@ -69,9 +69,10 @@ usage(void) eprintf("usage: %s [-p] username\n", argv0); } -// ?man login: begin terminal session +// ?man login: log into the system // ?man arguments: username -// ?man authenticate and start a session on the system +// ?man login logs the username into the system. +// ?man It sets HOME, SHELL, USER, LOGNAME and the PATH environment variables and invokes the login shell as specified in /etc/passwd. int main(int argc, char *argv[]) { @@ -83,7 +84,7 @@ main(int argc, char *argv[]) int pflag = 0; ARGBEGIN { - // ?man -p: preserve file attributes + // ?man -p: Preserve the environment. case 'p': pflag = 1; break; diff --git a/cmd/pseudo/md5sum.c b/cmd/pseudo/md5sum.c @@ -33,13 +33,13 @@ main(int argc, char *argv[]) uint8_t md[MD5_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/mktemp.c b/cmd/pseudo/mktemp.c @@ -27,11 +27,11 @@ main(int argc, char *argv[]) size_t len; ARGBEGIN { - // ?man -d: specify directory + // ?man -d: create a temporary directory instead of a file case 'd': dflag = 1; break; - // ?man -p:dir: preserve file attributes + // ?man -p:directory: use directory as the path prefix and imply -t case 'p': pflag = 1; pdir = EARGF(usage()); @@ -40,11 +40,11 @@ main(int argc, char *argv[]) case 'q': qflag = 1; break; - // ?man -t: sort or specify timestamp + // ?man -t: generate a path rooted in a temporary directory case 't': tflag = 1; break; - // ?man -u: unbuffered output + // ?man -u: unlink the file before exiting case 'u': uflag = 1; break; diff --git a/cmd/pseudo/pidof.c b/cmd/pseudo/pidof.c @@ -28,9 +28,9 @@ usage(void) eprintf("usage: %s [-o pid1,pid2,...pidN] [-s] [program...]\n", argv0); } -// ?man pidof: find process ids -// ?man arguments: -o pid1 -// ?man find the process identity numbers of running programs +// ?man pidof: find the process id of a running program +// ?man arguments: [program ...] +// ?man pidof finds the process id's of the named programs and prints them to stdout. int main(int argc, char *argv[]) { @@ -44,11 +44,11 @@ main(int argc, char *argv[]) struct pidentry *pe; ARGBEGIN { - // ?man -s: silent mode or print summary + // ?man -s: Single shot - this instructs the program to only return one process id. case 's': sflag = 1; break; - // ?man -o:str: specify output file + // ?man -o:pid: Tell pidof to omit processes with that process id. The special pid %PPID can be used to name the parent process of the pidof program. case 'o': oflag = 1; arg = EARGF(usage()); diff --git a/cmd/pseudo/respawn.c b/cmd/pseudo/respawn.c @@ -32,7 +32,7 @@ usage(void) } // ?man respawn: restart command on exit -// ?man arguments: cmd [args... +// ?man arguments: cmd [args ...] // ?man run a command and restart it automatically when it exits int main(int argc, char *argv[]) diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c @@ -90,17 +90,17 @@ main(int argc, char *argv[]) const char *starts = "1", *steps = "1", *ends = "1", *sep = "\n"; ARGBEGIN { - // ?man -f:str: force the operation + // ?man -f:fmt: use fmt as the output format case 'f': if (!validfmt(tmp=EARGF(usage()))) eprintf("%s: invalid format\n", tmp); fmt = tmp; break; - // ?man -s:str: silent mode or print summary + // ?man -s:sep: print sep between output numbers case 's': sep = EARGF(usage()); break; - // ?man -w: wait for completion + // ?man -w: pad all numbers to the same width case 'w': wflag = 1; break; diff --git a/cmd/pseudo/setsid.c b/cmd/pseudo/setsid.c @@ -15,7 +15,7 @@ usage(void) } // ?man setsid: run in new session -// ?man arguments: cmd [arg ... +// ?man arguments: cmd [arg ...] // ?man run a program in a new session int main(int argc, char *argv[]) diff --git a/cmd/pseudo/sha1sum.c b/cmd/pseudo/sha1sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA1_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha224sum.c b/cmd/pseudo/sha224sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA224_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha256sum.c b/cmd/pseudo/sha256sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA256_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha384sum.c b/cmd/pseudo/sha384sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA384_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512-224sum.c b/cmd/pseudo/sha512-224sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_224_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512-256sum.c b/cmd/pseudo/sha512-256sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_256_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512sum.c b/cmd/pseudo/sha512sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: specify block size or base directory + // ?man -b: accepted for compatibility; ignored case 'b': - // ?man -t: sort or specify timestamp + // ?man -t: accepted for compatibility; ignored case 't': /* ignore */ break; - // ?man -c: print count or perform stdout action + // ?man -c: read checksums from files and verify them case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -801,8 +801,8 @@ usage(void) } // ?man tar: tape archiver -// ?man arguments: x | t | -x | -t] [file ... -// ?man tar [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] [-T file] [-X file] path ... [-f file] +// ?man synopsis: [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p] [-f file] [file ...] +// ?man synopsis: [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] path ... [-f file] // ?man manipulate tape archive files int main(int argc, char *argv[]) @@ -834,32 +834,32 @@ main(int argc, char *argv[]) case 't': mode = ARGC(); break; - // ?man -C:dir: specify option flag + // ?man -C:dir: change to dir before processing files case 'C': dir = EARGF(usage()); break; - // ?man -f:file: specify archive file + // ?man -f:file: use file as the archive instead of standard input or output case 'f': file = EARGF(usage()); break; - // ?man -m: specify mode or limit + // ?man -m: do not preserve modification times when extracting case 'm': mflag = 1; break; - // ?man -J: specify option flag + // ?man -J: use xz compression or decompression case 'J': - // ?man -Z: specify option flag + // ?man -Z: use compress compression or decompression case 'Z': - // ?man -a: print or show all entries + // ?man -a: use lzma compression or decompression case 'a': - // ?man -j: specify option flag + // ?man -j: use bzip2 compression or decompression case 'j': - // ?man -z: specify option flag + // ?man -z: use gzip compression or decompression case 'z': filtermode = ARGC(); filtertool = filtertools[filtermode]; break; - // ?man -h: suppress headers or print help + // ?man -h: follow symbolic links when archiving case 'h': #if FEATURE_TAR_CREATE r.follow = 'L'; @@ -869,7 +869,7 @@ main(int argc, char *argv[]) case 'v': vflag = 1; break; - // ?man -p: preserve file attributes + // ?man -p: preserve permissions; this is the default behavior case 'p': break; /* do nothing as already default behaviour */ #if FEATURE_TAR_TO_STDOUT diff --git a/cmd/pseudo/truncate.c b/cmd/pseudo/truncate.c @@ -16,9 +16,9 @@ usage(void) eprintf("usage: %s [-c] -s size file...\n", argv0); } -// ?man truncate: set file size -// ?man arguments: -s size file... -// ?man shrink or extend a file to a specified size +// ?man truncate: shrink or extend the size of a file to the specified size +// ?man synopsis: [-c] -s size file ... +// ?man truncate shrinks or extends the size of each file specified size. A file argument that does not exist is created. If a file is larger than the specified size, the extra data is lost. If a file is shorter, it is extended and the extended part reads as zero bytes. int main(int argc, char *argv[]) { @@ -27,12 +27,12 @@ main(int argc, char *argv[]) long size = 0; ARGBEGIN { - // ?man -s:num: silent mode or print summary + // ?man -s:size: Set or adjust the file size by size bytes. case 's': sflag = 1; size = estrtol(EARGF(usage()), 10); break; - // ?man -c: print count or perform stdout action + // ?man -c: Do not create any files. case 'c': cflag = 1; break; diff --git a/cmd/pseudo/which.c b/cmd/pseudo/which.c @@ -80,7 +80,7 @@ main(int argc, char *argv[]) int found = 0, foundall = 1; ARGBEGIN { - // ?man -a: print or show all entries + // ?man -a: search all PATH directories instead of stopping at the first match case 'a': aflag = 1; break; diff --git a/cmd/pseudo/xinstall.c b/cmd/pseudo/xinstall.c @@ -85,7 +85,9 @@ usage(void) } // ?man xinstall: copy files and set attributes -// ?man arguments: (-d dir ... | (-t dest source ... | source ... dest)) +// ?man synopsis: [-g group] [-o owner] [-m mode] -d dir ... +// ?man synopsis: [-g group] [-o owner] [-m mode] [-D] -t dest source ... +// ?man synopsis: [-g group] [-o owner] [-m mode] [-D] source ... dest // ?man copy files and set their permissions and ownership int main(int argc, char *argv[]) @@ -101,35 +103,35 @@ main(int argc, char *argv[]) char *p; ARGBEGIN { - // ?man -c: print count or perform stdout action + // ?man -c: accepted for compatibility; has no effect case 'c': /* no-op for compatibility */ break; - // ?man -d: specify directory + // ?man -d: create directories instead of installing files case 'd': dflag = 1; break; - // ?man -D: specify option flag + // ?man -D: create leading directories for the destination before installing case 'D': Dflag = 1; break; - // ?man -s: silent mode or print summary + // ?man -s: accepted for compatibility; has no effect case 's': /* no-op for compatibility */ break; - // ?man -g:str: specify option flag + // ?man -g:group: set the installed file group to group case 'g': gflag = EARGF(usage()); break; - // ?man -o:str: specify output file + // ?man -o:owner: set the installed file owner to owner case 'o': oflag = EARGF(usage()); break; - // ?man -m:str: specify mode or limit + // ?man -m:mode: set the installed file mode to mode case 'm': mflag = EARGF(usage()); break; - // ?man -t:str: sort or specify timestamp + // ?man -t:dest: install source files into the destination directory dest case 't': tflag = EARGF(usage()); break; diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c @@ -24,7 +24,7 @@ usage(void) } // ?man mknod: create special files -// ?man arguments: name b|c|u major minor +// ?man arguments: name <type> major minor // ?man create block or character special files int main(int argc, char *argv[]) diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c @@ -25,9 +25,11 @@ usage(void) eprintf("usage: %s [-lp] [username]\n", argv0); } -// ?man su: run command with substitute user id +// ?man su: run a command with a substitute user and group ID // ?man arguments: username -// ?man run a shell or command with another user id +// ?man su allows to run commands with a substitute user and group ID. +// ?man When called without arguments, su defaults to running an interactive shell as root. +// ?man For backward compatibility su defaults to not change the current directory and to only set the environment variables HOME and SHELL plus USER and LOGNAME if the target username is not root. int main(int argc, char *argv[]) { @@ -38,11 +40,11 @@ main(int argc, char *argv[]) uid_t uid; ARGBEGIN { - // ?man -l: list in long format + // ?man -l: Starts the shell as login shell with an environment similar to a real login. case 'l': lflag = 1; break; - // ?man -p: preserve file attributes + // ?man -p: Preserves the whole environment. This option is ignored if the -l option is specified. case 'p': pflag = 1; break; diff --git a/scripts/mkman/djot/assemble.go b/scripts/mkman/djot/assemble.go @@ -1,1135 +0,0 @@ -package djot - -import ( - "bytes" - "strconv" - "strings" -) - -type Assembler struct { - doc *Document - stack []int32 - - pendingAttr []Attribute - sectionStack []int16 - - references map[string]Reference - lastClosedNode int32 - - footnoteLabels map[string]int - usedFootnotes []string - footnoteContent map[string]int32 - - usedIDs map[string]bool - headingIDs map[int32]string - - currentTableAlignments []uint32 -} - -func (a *Assembler) Assemble(events []Event) { - a.doc.Nodes = make([]Node, 0, len(events)/2+8) - a.doc.Attributes = make([]Attribute, 0, 16) - a.doc.References = make(map[string]Reference) - a.doc.Extra = make([]byte, 0, 64) - a.stack = make([]int32, 0, 16) - a.pendingAttr = make([]Attribute, 0, 8) - a.sectionStack = make([]int16, 0, 8) - a.references = make(map[string]Reference) - a.lastClosedNode = -1 - a.footnoteLabels = make(map[string]int) - a.usedFootnotes = make([]string, 0, 8) - a.footnoteContent = make(map[string]int32) - a.usedIDs = make(map[string]bool) - a.headingIDs = make(map[int32]string) - - a.collectReferences(events) - a.collectHeadingReferences(events) - - rootIdx := a.addNode(NodeDoc, 0, 0) - a.stack = append(a.stack, rootIdx) - - type listTightState struct { - nodeIdx int32 - blanklines bool - } - var listTightStack []listTightState - - i := 0 - for i < len(events) { - ev := events[i] - - if len(listTightStack) > 0 { - top := &listTightStack[len(listTightStack)-1] - switch ev.Type { - case EvBlankLine: - top.blanklines = true - case EvOpenList, EvCloseList: - top.blanklines = false - case EvOpenListItem, EvCloseListItem: - default: - if top.blanklines { - a.doc.Nodes[top.nodeIdx].Data &= ^DataListTight - } - top.blanklines = false - } - } - - switch ev.Type { - case EvOpenAttributes: - i = a.parseAttributes(events, i) - case EvOpenInlineAttributes: - i = a.parseAttributes(events, i) - if a.lastClosedNode != -1 && len(a.pendingAttr) > 0 { - if a.doc.Nodes[a.lastClosedNode].Type == NodeStr { - nodeIdx := a.lastClosedNode - content := a.doc.Source[a.doc.Nodes[nodeIdx].Start : a.doc.Nodes[nodeIdx].End+1] - if len(content) == 0 || isSpace(content[len(content)-1]) { - a.pendingAttr = a.pendingAttr[:0] - } else { - lastWordStart := -1 - for j := len(content) - 1; j >= 0; j-- { - if isSpace(content[j]) { - lastWordStart = j + 1 - break - } - } - if lastWordStart == -1 { - lastWordStart = 0 - } - - if lastWordStart > 0 { - origStart := a.doc.Nodes[nodeIdx].Start - origEnd := a.doc.Nodes[nodeIdx].End - newEnd := origStart + int32(lastWordStart) - 1 - - spanIdx := a.addNode(NodeSpan, origStart+int32(lastWordStart), origEnd) - wordIdx := a.addNode(NodeStr, origStart+int32(lastWordStart), origEnd) - - a.doc.Nodes[nodeIdx].End = newEnd - a.doc.Nodes[spanIdx].Child = wordIdx - - parentIdx := a.stack[len(a.stack)-1] - a.linkToParent(parentIdx, spanIdx) - - a.lastClosedNode = spanIdx - } else if lastWordStart == 0 { - origStart := a.doc.Nodes[nodeIdx].Start - origEnd := a.doc.Nodes[nodeIdx].End - childIdx := a.addNode(NodeStr, origStart, origEnd) - a.doc.Nodes[nodeIdx].Type = NodeSpan - a.doc.Nodes[nodeIdx].Child = childIdx - } - } - } - a.applyPendingAttr(a.lastClosedNode) - } else { - a.pendingAttr = a.pendingAttr[:0] - } - case EvOpenPara: - idx := a.openNode(NodePara, ev.Start) - a.applyPendingAttr(idx) - case EvClosePara: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenHeading: - level := int16(ev.End - ev.Start + 1) - a.handleHeadingOpen(level, ev.Start) - case EvCloseHeading: - idx := a.closeNode(ev.End) - a.generateID(idx, a.doc.Nodes[idx].Start) - a.lastClosedNode = idx - case EvOpenBlockQuote: - idx := a.openNode(NodeBlockQuote, ev.Start) - a.applyPendingAttr(idx) - case EvCloseBlockQuote: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenList: - marker := byte(ev.End) - ntype := NodeBulletList - if isOrderedMarker(marker) { - ntype = NodeOrderedList - } else if marker == ':' { - ntype = NodeDefinitionList - } - idx := a.openNode(ntype, ev.Start) - a.applyPendingAttr(idx) - a.doc.Nodes[idx].Data |= DataListTight - a.setStyleFromMarker(idx, marker) - listTightStack = append(listTightStack, listTightState{nodeIdx: idx}) - - if ntype == NodeOrderedList && i+1 < len(events) && events[i+1].Type == EvNone { - i++ - startNum := int(events[i].End) - if startNum != 1 { - a.doc.Nodes[idx].Data |= uint32(startNum) << 16 - } - } - case EvCloseList: - a.lastClosedNode = a.closeNode(ev.Start) - if len(listTightStack) > 0 { - listTightStack = listTightStack[:len(listTightStack)-1] - } - case EvOpenListItem: - pIdx := a.stack[len(a.stack)-1] - ntype := NodeListItem - if a.doc.Nodes[pIdx].Type == NodeDefinitionList { - ntype = NodeDefinitionListItem - } - idx := a.openNode(ntype, ev.Start) - a.applyPendingAttr(idx) - if ev.End > 0 && ntype == NodeListItem { - a.doc.Nodes[idx].Type = NodeTaskListItem - if ev.End == 2 { - a.doc.Nodes[idx].Data |= DataTaskChecked - } - pIdx := a.stack[len(a.stack)-2] - if a.doc.Nodes[pIdx].Type == NodeBulletList { - a.doc.Nodes[pIdx].Type = NodeTaskList - } - } - case EvCloseListItem: - idx := a.stack[len(a.stack)-1] - if a.doc.Nodes[idx].Type == NodeDefinitionListItem { - a.handleDefinitionListItem(idx) - } - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenCodeBlock, EvOpenRawBlock: - ntype := NodeCodeBlock - closeType := EvCloseCodeBlock - if ev.Type == EvOpenRawBlock { - ntype = NodeRawBlock - closeType = EvCloseRawBlock - } - idx := a.openNode(ntype, ev.Start) - a.applyPendingAttr(idx) - - j := i + 1 - contentStart := int32(-1) - foundStartMarker := false - for j < len(events) { - if !foundStartMarker && events[j].Type == EvNone { - foundStartMarker = true - } else if events[j].Type == EvStr { - if contentStart == -1 { - contentStart = events[j].Start - } - } else if events[j].Type == closeType { - break - } - j++ - } - - if contentStart != -1 { - var buf bytes.Buffer - for k := i + 1; k < j; k++ { - if events[k].Type == EvStr { - buf.Write(a.doc.Source[events[k].Start : events[k].End+1]) - } - } - extraStart := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, buf.Bytes()...) - a.doc.Nodes[idx].Start = ^extraStart - a.doc.Nodes[idx].End = int32(len(a.doc.Extra)) - 1 - } else { - a.doc.Nodes[idx].Start = -1 - a.doc.Nodes[idx].End = -1 - } - - if ntype == NodeRawBlock && idx != -1 { - node := &a.doc.Nodes[idx] - if node.Attr != -1 { - for k := uint16(0); k < node.AttrCount; k++ { - attr := &a.doc.Attributes[node.Attr+int32(k)] - if attr.KeyStart == -2 { - val := string(a.getAttrVal(*attr)) - if strings.HasPrefix(val, "=") { - attr.KeyStart = -3 - } - } - } - } - } - a.closeNode(ev.End) - i = j - case EvOpenDiv: - idx := a.openNode(NodeDiv, ev.Start) - a.applyPendingAttr(idx) - case EvCloseDiv: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenTable: - idx := a.openNode(NodeTable, ev.Start) - a.applyPendingAttr(idx) - case EvCloseTable: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenCaption: - idx := int32(-1) - if a.lastClosedNode != -1 && a.doc.Nodes[a.lastClosedNode].Type == NodeTable { - tableIdx := a.lastClosedNode - captionIdx := a.addNode(NodeCaption, ev.Start, -1) - a.linkToParent(tableIdx, captionIdx) - a.stack = append(a.stack, captionIdx) - a.lastClosedNode = -1 - idx = captionIdx - } else { - idx = a.openNode(NodeCaption, ev.Start) - } - a.applyPendingAttr(idx) - case EvCloseCaption: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenRow: - a.openNode(NodeRow, ev.Start) - case EvCloseRow: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenCell: - idx := a.openNode(NodeCell, ev.Start) - a.applyPendingAttr(idx) - - col := 0 - curr := a.doc.Nodes[a.stack[len(a.stack)-2]].Child - for curr != -1 && curr != idx { - curr = a.doc.Nodes[curr].Next - col++ - } - if col < len(a.currentTableAlignments) { - a.doc.Nodes[idx].Data &= ^(DataAlignLeft | DataAlignCenter | DataAlignRight) - a.doc.Nodes[idx].Data |= a.currentTableAlignments[col] - } - case EvCloseCell: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenFootnote: - j := i + 1 - label := "" - if j < len(events) && events[j].Type == EvStr { - content := a.doc.Source[events[j].Start : events[j].End+1] - if len(content) > 0 && content[0] == '[' && content[1] == '^' { - closeIdx := bytes.IndexByte(content, ']') - if closeIdx != -1 { - label = normalizeLabel(string(content[2:closeIdx])) - } - } - } - idx := a.openNode(NodeFootnote, ev.Start) - if label != "" { - a.footnoteContent[label] = idx - } - a.applyPendingAttr(idx) - case EvCloseFootnote: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenReferenceDefinition: - idx := a.openNode(NodeReference, ev.Start) - a.applyPendingAttr(idx) - case EvCloseReferenceDefinition: - a.closeNode(ev.End) - case EvOpenLinkText: - idx := a.openNode(NodeLink, ev.Start) - a.applyPendingAttr(idx) - case EvCloseLinkText: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenImageText: - idx := a.openNode(NodeImage, ev.Start) - a.applyPendingAttr(idx) - case EvCloseImageText: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenSpan: - idx := a.openNode(NodeSpan, ev.Start) - a.applyPendingAttr(idx) - case EvCloseSpan: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenDoubleQuoted: - a.openNode(NodeDoubleQuoted, ev.Start) - case EvCloseDoubleQuoted: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenSingleQuoted: - a.openNode(NodeSingleQuoted, ev.Start) - case EvCloseSingleQuoted: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenMark: - idx := a.openNode(NodeMark, ev.Start) - a.applyPendingAttr(idx) - case EvCloseMark: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenInsert: - idx := a.openNode(NodeInsert, ev.Start) - a.applyPendingAttr(idx) - case EvCloseInsert: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenDelete: - idx := a.openNode(NodeDelete, ev.Start) - a.applyPendingAttr(idx) - case EvCloseDelete: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenDestination: - a.addLeafNode(NodeUrl, ev.Start, ev.End) - case EvUrl, EvEmail: - idx := a.openNode(NodeLink, ev.Start) - a.applyPendingAttr(idx) - - destType := NodeUrl - if ev.Type == EvEmail { - destType = NodeEmail - } - destIdx := a.addNode(destType, ev.Start, ev.End) - a.linkToParent(idx, destIdx) - - strIdx := a.addNode(NodeStr, ev.Start, ev.End) - a.linkToParent(idx, strIdx) - - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenReference: - label := string(a.doc.Source[ev.Start : ev.End+1]) - if label == "" { - var buf strings.Builder - a.collectPlainText(a.stack[len(a.stack)-1], &buf) - label = buf.String() - } - label = normalizeLabel(label) - if ref, ok := a.references[label]; ok { - a.addLeafNode(NodeUrl, ref.DestStart, ref.DestEnd) - if len(ref.Attributes) > 0 { - parentIdx := a.stack[len(a.stack)-1] - a.pendingAttr = append(a.pendingAttr, ref.Attributes...) - a.applyPendingAttr(parentIdx) - } - } - case EvFootnoteReference: - label := string(a.doc.Source[ev.Start+2 : ev.End]) - num, ok := a.footnoteLabels[label] - if !ok { - num = len(a.usedFootnotes) + 1 - a.footnoteLabels[label] = num - a.usedFootnotes = append(a.usedFootnotes, label) - } - idx := a.addNode(NodeFootnoteReference, ev.Start, ev.End) - a.doc.Nodes[idx].Data = uint32(num) - parentIdx := a.stack[len(a.stack)-1] - a.linkToParent(parentIdx, idx) - case EvSmartPunctuation: - a.addLeafNode(NodeSmartPunctuation, ev.Start, ev.End) - case EvInlineMath: - a.addLeafNode(NodeInlineMath, ev.Start, ev.End) - case EvDisplayMath: - a.addLeafNode(NodeDisplayMath, ev.Start, ev.End) - case EvRawInline: - idx := a.addNode(NodeRawInline, ev.Start, ev.End) - a.linkToParent(a.stack[len(a.stack)-1], idx) - a.lastClosedNode = idx - i++ - for i < len(events) && events[i].Type != EvRawInline { - i++ - } - case EvOpenVerbatim: - a.openNode(NodeVerbatim, ev.Start) - case EvCloseVerbatim: - a.lastClosedNode = a.closeNode(ev.End) - case EvSoftBreak: - a.addLeafNode(NodeSoftBreak, ev.Start, ev.End) - case EvHardBreak: - a.addLeafNode(NodeHardBreak, ev.Start, ev.End) - case EvNonBreakingSpace: - a.addLeafNode(NodeNonBreakingSpace, ev.Start, ev.End) - case EvThematicBreak: - idx := a.addNode(NodeThematicBreak, ev.Start, ev.End) - a.linkToParent(a.stack[len(a.stack)-1], idx) - a.applyPendingAttr(idx) - case EvBlankLine: - case EvStr: - skipThisStr := false - if i > 0 && events[i-1].Type == EvOpenFootnote { - content := a.doc.Source[ev.Start : ev.End+1] - if len(content) > 0 && content[0] == '[' && len(content) > 1 && content[1] == '^' { - if bytes.Contains(content, []byte("]:")) { - skipThisStr = true - } - } - } - if !skipThisStr { - tipIdx := a.stack[len(a.stack)-1] - if a.doc.Nodes[tipIdx].Type == NodeTable { - a.handleTableSeparator(ev.Start, ev.End) - } else { - a.addLeafNode(NodeStr, ev.Start, ev.End) - } - } - case EvSymb: - a.addLeafNode(NodeSymb, ev.Start, ev.End) - case EvOpenEmph: - idx := a.openNode(NodeEmph, ev.Start) - a.applyPendingAttr(idx) - case EvCloseEmph: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenStrong: - idx := a.openNode(NodeStrong, ev.Start) - a.applyPendingAttr(idx) - case EvCloseStrong: - a.lastClosedNode = a.closeNode(ev.End) - case EvEscape: - a.addLeafNode(NodeStr, ev.Start+1, ev.End) - case EvOpenSuperscript: - a.openNode(NodeSuperscript, ev.Start) - case EvCloseSuperscript: - a.lastClosedNode = a.closeNode(ev.End) - case EvOpenSubscript: - a.openNode(NodeSubscript, ev.Start) - case EvCloseSubscript: - a.lastClosedNode = a.closeNode(ev.End) - } - i++ - } - - for _, label := range a.usedFootnotes { - if contentIdx, ok := a.footnoteContent[label]; ok { - a.linkToParent(rootIdx, contentIdx) - } - } - - a.doc.UsedFootnotes = a.usedFootnotes - a.doc.FootnoteContent = a.footnoteContent - a.doc.References = a.references - - if len(a.doc.Source) > 0 { - a.doc.Nodes[rootIdx].End = int32(len(a.doc.Source) - 1) - } -} - -func normalizeLabel(label string) string { - return strings.Join(strings.Fields(label), " ") -} - -func unescapeBytes(b []byte) []byte { - var res []byte - escaped := false - for _, ch := range b { - if escaped { - res = append(res, ch) - escaped = false - } else if ch == '\\' { - escaped = true - } else { - res = append(res, ch) - } - } - return res -} - -func (a *Assembler) collectReferences(events []Event) { - var pendingAttr []Attribute - for i := 0; i < len(events); i++ { - ev := events[i] - switch ev.Type { - case EvOpenAttributes, EvOpenInlineAttributes: - i = a.parseAttributesTo(events, i, &pendingAttr) - continue - case EvOpenPara, EvOpenBlockQuote, EvOpenList, EvOpenListItem, EvOpenCodeBlock, EvOpenDiv, EvOpenTable, EvOpenCaption, EvOpenRow, EvOpenCell, EvOpenHeading: - pendingAttr = pendingAttr[:0] - case EvOpenReferenceDefinition: - var content string - j := i + 1 - for j < len(events) && events[j].Type != EvCloseReferenceDefinition { - if events[j].Type == EvStr || events[j].Type == EvText { - content = string(a.doc.Source[events[j].Start : events[j].End+1]) - } - j++ - } - - if content == "" { - lineStart := events[i].Start - lineEnd := lineStart - for lineEnd < int32(len(a.doc.Source)) && a.doc.Source[lineEnd] != '\n' { - lineEnd++ - } - if lineEnd > lineStart { - content = string(a.doc.Source[lineStart:lineEnd]) - } - } - - if len(content) > 0 && content[0] == '[' { - closeIdx := strings.IndexByte(content, ']') - if closeIdx != -1 && closeIdx+1 < len(content) && content[closeIdx+1] == ':' { - label := normalizeLabel(content[1:closeIdx]) - value := content[closeIdx+2:] - - value = strings.ReplaceAll(value, "\r\n", "\n") - value = strings.ReplaceAll(value, "\r", "\n") - parts := strings.Split(value, "\n") - var cleanedParts []string - for _, p := range parts { - cleaned := strings.TrimSpace(p) - if len(cleaned) > 0 { - cleanedParts = append(cleanedParts, cleaned) - } - } - cleanValue := strings.Join(cleanedParts, "") - valStart := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, []byte(cleanValue)...) - valEnd := int32(len(a.doc.Extra)) - 1 - - refAttrs := make([]Attribute, len(pendingAttr)) - copy(refAttrs, pendingAttr) - - a.references[label] = Reference{ - DestStart: ^valStart, - DestEnd: valEnd, - Attributes: refAttrs, - } - pendingAttr = pendingAttr[:0] - } - } - i = j - case EvOpenFootnote: - j := i + 1 - if j < len(events) && events[j].Type == EvStr { - content := a.doc.Source[events[j].Start : events[j].End+1] - if len(content) > 0 && content[0] == '[' && content[1] == '^' { - closeIdx := bytes.IndexByte(content, ']') - if closeIdx != -1 && closeIdx+1 < len(content) && content[closeIdx+1] == ':' { - label := normalizeLabel(string(content[2:closeIdx])) - a.footnoteContent[label] = -2 - } - } - } - pendingAttr = pendingAttr[:0] - } - } -} - -func (a *Assembler) parseAttributesTo(events []Event, startIdx int, target *[]Attribute) int { - i := startIdx + 1 - for i < len(events) && events[i].Type != EvCloseAttributes { - ev := events[i] - switch ev.Type { - case EvAttrIdMarker: - *target = append(*target, Attribute{ - KeyStart: -1, - ValStart: ev.Start, - ValEnd: ev.End, - }) - case EvAttrClassMarker: - *target = append(*target, Attribute{ - KeyStart: -2, - ValStart: ev.Start, - ValEnd: ev.End, - }) - case EvAttrKey: - keyEv := ev - if keyEv.Start < int32(len(a.doc.Source)) && a.doc.Source[keyEv.Start] == '=' { - *target = append(*target, Attribute{ - KeyStart: -3, - ValStart: keyEv.Start + 1, - ValEnd: keyEv.End, - }) - } else { - for i+1 < len(events) && events[i+1].Type != EvCloseAttributes { - i++ - if events[i].Type == EvAttrValue { - *target = append(*target, Attribute{ - KeyStart: keyEv.Start, - KeyEnd: keyEv.End, - ValStart: events[i].Start, - ValEnd: events[i].End, - }) - break - } - } - } - } - i++ - } - return i -} - -func (a *Assembler) collectHeadingReferences(events []Event) { - tempAs := &Assembler{doc: a.doc, references: a.references, usedIDs: make(map[string]bool)} - i := 0 - for i < len(events) { - ev := events[i] - switch ev.Type { - case EvOpenAttributes: - i = tempAs.parseAttributes(events, i) - continue - case EvOpenPara, EvOpenBlockQuote, EvOpenList, EvOpenListItem, EvOpenCodeBlock, EvOpenDiv, EvOpenTable, EvOpenCaption, EvOpenRow, EvOpenCell: - if len(tempAs.pendingAttr) > 0 { - for _, attr := range tempAs.pendingAttr { - if attr.KeyStart == -1 { - var id string - if attr.ValStart < 0 { - id = string(a.doc.Extra[^attr.ValStart : attr.ValEnd+1]) - } else { - id = string(a.doc.Source[attr.ValStart : attr.ValEnd+1]) - } - tempAs.usedIDs[id] = true - break - } - } - tempAs.pendingAttr = tempAs.pendingAttr[:0] - } - case EvOpenHeading: - headingStart := ev.Start - j := i + 1 - var buf strings.Builder - for j < len(events) && events[j].Type != EvCloseHeading { - if events[j].Type == EvStr { - buf.Write(a.doc.Source[events[j].Start : events[j].End+1]) - } else if events[j].Type == EvSoftBreak { - buf.WriteByte('\n') - } - j++ - } - text := buf.String() - label := normalizeLabel(text) - - var manualID string - if len(tempAs.pendingAttr) > 0 { - for _, attr := range tempAs.pendingAttr { - if attr.KeyStart == -1 { - if attr.ValStart < 0 { - manualID = string(a.doc.Extra[^attr.ValStart : attr.ValEnd+1]) - } else { - manualID = string(a.doc.Source[attr.ValStart : attr.ValEnd+1]) - } - tempAs.usedIDs[manualID] = true - break - } - } - tempAs.pendingAttr = tempAs.pendingAttr[:0] - } - - ident := manualID - if ident == "" { - base := a.slugify(text) - ident = base - if ident == "" { - ident = "s" - } - if tempAs.usedIDs[ident] || base == "" { - k := 1 - if base == "" { - ident = "s-1" - } else { - ident = base + "-1" - } - for tempAs.usedIDs[ident] { - k++ - ident = base + "-" + strconv.Itoa(k) - if base == "" { - ident = "s-" + strconv.Itoa(k) - } - } - } - tempAs.usedIDs[ident] = true - } - - a.headingIDs[headingStart] = ident - - if _, ok := a.references[label]; !ok { - start := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, '#') - a.doc.Extra = append(a.doc.Extra, []byte(ident)...) - a.references[label] = Reference{ - DestStart: ^start, - DestEnd: int32(len(a.doc.Extra)) - 1, - } - } - i = j - } - i++ - } -} - -func (a *Assembler) generateID(idx int32, start int32) { - node := &a.doc.Nodes[idx] - if node.Data&DataNoAutoID != 0 { - return - } - - parentIdx := a.stack[len(a.stack)-1] - targetIdx := idx - if a.doc.Nodes[parentIdx].Type == NodeSection { - targetIdx = parentIdx - } - - if a.doc.Nodes[targetIdx].Attr != -1 { - for j := uint16(0); j < a.doc.Nodes[targetIdx].AttrCount; j++ { - attr := a.doc.Attributes[a.doc.Nodes[targetIdx].Attr+int32(j)] - if attr.KeyStart == -1 { - return - } - } - } - - ident, ok := a.headingIDs[start] - if !ok { - return - } - - valStart := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, []byte(ident)...) - valEnd := int32(len(a.doc.Extra)) - 1 - - attr := Attribute{ - KeyStart: -1, - ValStart: ^valStart, - ValEnd: valEnd, - } - - a.pendingAttr = append(a.pendingAttr, attr) - a.applyPendingAttr(targetIdx) -} - -func (a *Assembler) collectPlainText(idx int32, buf *strings.Builder) { - curr := a.doc.Nodes[idx].Child - for curr != -1 { - node := a.doc.Nodes[curr] - if node.Type == NodeStr { - buf.Write(a.doc.Source[node.Start : node.End+1]) - } else if node.Type == NodeSoftBreak { - buf.WriteByte('\n') - } else { - a.collectPlainText(curr, buf) - } - curr = a.doc.Nodes[curr].Next - } -} - -func (a *Assembler) slugify(text string) string { - var res []rune - lastWasSpec := false - for _, r := range text { - isSpec := strings.ContainsRune("][~!@#$%^&*(){}`,.<>\\|=+/? \t\r\n", r) - if isSpec { - if !lastWasSpec { - res = append(res, ' ') - } - lastWasSpec = true - } else { - res = append(res, r) - lastWasSpec = false - } - } - s := strings.TrimSpace(string(res)) - return strings.ReplaceAll(s, " ", "-") -} - -func (a *Assembler) handleTableSeparator(start, end int32) { - parentIdx := a.stack[len(a.stack)-1] - curr := a.doc.Nodes[parentIdx].Child - var lastRow int32 = -1 - for curr != -1 { - if a.doc.Nodes[curr].Type == NodeRow { - lastRow = curr - } - curr = a.doc.Nodes[curr].Next - } - - line := a.doc.Source[start : end+1] - parts := bytes.Split(line, []byte("|")) - - newAlignments := make([]uint32, 0) - for _, part := range parts { - part = bytes.TrimSpace(part) - if len(part) == 0 { - continue - } - - align := uint32(0) - left := part[0] == ':' - right := part[len(part)-1] == ':' - - if left && right { - align = DataAlignCenter - } else if left { - align = DataAlignLeft - } else if right { - align = DataAlignRight - } - newAlignments = append(newAlignments, align) - } - a.currentTableAlignments = newAlignments - - if lastRow != -1 { - cell := a.doc.Nodes[lastRow].Child - col := 0 - for cell != -1 { - a.doc.Nodes[cell].Data |= DataCellHeader - if col < len(a.currentTableAlignments) { - a.doc.Nodes[cell].Data &= ^(DataAlignLeft | DataAlignCenter | DataAlignRight) - a.doc.Nodes[cell].Data |= a.currentTableAlignments[col] - } - cell = a.doc.Nodes[cell].Next - col++ - } - } -} - -func (a *Assembler) handleHeadingOpen(level int16, start int32) { - for len(a.sectionStack) > 0 && a.sectionStack[len(a.sectionStack)-1] >= level { - a.stack = a.stack[:len(a.stack)-1] - a.sectionStack = a.sectionStack[:len(a.sectionStack)-1] - } - - parentIdx := a.stack[len(a.stack)-1] - parentType := a.doc.Nodes[parentIdx].Type - - if parentType == NodeDoc || parentType == NodeSection { - sIdx := a.openNode(NodeSection, start) - a.sectionStack = append(a.sectionStack, level) - a.applyPendingAttr(sIdx) - } - - hIdx := a.openNode(NodeHeading, start) - a.doc.Nodes[hIdx].Level = level - if len(a.pendingAttr) > 0 { - a.doc.Nodes[hIdx].Data |= DataNoAutoID - a.applyPendingAttr(hIdx) - } -} - -func (a *Assembler) parseAttributes(events []Event, startIdx int) int { - i := startIdx + 1 - for i < len(events) && events[i].Type != EvCloseAttributes { - ev := events[i] - switch ev.Type { - case EvAttrIdMarker: - a.pendingAttr = append(a.pendingAttr, Attribute{ - KeyStart: -1, - ValStart: ev.Start, - ValEnd: ev.End, - }) - case EvAttrClassMarker: - a.pendingAttr = append(a.pendingAttr, Attribute{ - KeyStart: -2, - ValStart: ev.Start, - ValEnd: ev.End, - }) - case EvAttrKey: - keyEv := ev - if keyEv.Start < int32(len(a.doc.Source)) && a.doc.Source[keyEv.Start] == '=' { - a.pendingAttr = append(a.pendingAttr, Attribute{ - KeyStart: -3, - ValStart: keyEv.Start + 1, - ValEnd: keyEv.End, - }) - } else { - for i+1 < len(events) && events[i+1].Type != EvCloseAttributes { - i++ - if events[i].Type == EvAttrValue { - rawVal := a.doc.Source[events[i].Start : events[i].End+1] - decodedVal := unescapeBytes(rawVal) - valStart := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, decodedVal...) - valEnd := int32(len(a.doc.Extra)) - 1 - a.pendingAttr = append(a.pendingAttr, Attribute{ - KeyStart: keyEv.Start, - KeyEnd: keyEv.End, - ValStart: ^valStart, - ValEnd: valEnd, - }) - break - } - } - } - } - i++ - } - return i -} - -func (a *Assembler) getAttrVal(attr Attribute) []byte { - if attr.ValStart < 0 { - return a.doc.Extra[^attr.ValStart : attr.ValEnd+1] - } - return a.doc.Source[attr.ValStart : attr.ValEnd+1] -} - -func (a *Assembler) applyPendingAttr(idx int32) { - if len(a.pendingAttr) == 0 { - return - } - - node := &a.doc.Nodes[idx] - var attrs []Attribute - if node.Attr != -1 { - for i := uint16(0); i < node.AttrCount; i++ { - attrs = append(attrs, a.doc.Attributes[node.Attr+int32(i)]) - } - } - - for _, newAttr := range a.pendingAttr { - if newAttr.KeyStart == -1 { - id := string(a.getAttrVal(newAttr)) - a.usedIDs[id] = true - } - - foundIdx := -1 - for i := range attrs { - if newAttr.KeyStart == -1 && attrs[i].KeyStart == -1 { - foundIdx = i - break - } else if newAttr.KeyStart == -2 && attrs[i].KeyStart == -2 { - foundIdx = i - break - } else if newAttr.KeyStart >= 0 && attrs[i].KeyStart >= 0 { - oldKey := a.doc.Source[attrs[i].KeyStart : attrs[i].KeyEnd+1] - newKey := a.doc.Source[newAttr.KeyStart : newAttr.KeyEnd+1] - if bytes.Equal(oldKey, newKey) { - foundIdx = i - break - } - } - } - - if newAttr.KeyStart == -2 && foundIdx != -1 { - oldVal := a.getAttrVal(attrs[foundIdx]) - newVal := a.getAttrVal(newAttr) - - start := int32(len(a.doc.Extra)) - a.doc.Extra = append(a.doc.Extra, oldVal...) - a.doc.Extra = append(a.doc.Extra, ' ') - a.doc.Extra = append(a.doc.Extra, newVal...) - end := int32(len(a.doc.Extra)) - 1 - - attrs[foundIdx].ValStart = ^start - attrs[foundIdx].ValEnd = end - } else if foundIdx != -1 { - attrs[foundIdx] = newAttr - } else { - attrs = append(attrs, newAttr) - } - } - - node.Attr = int32(len(a.doc.Attributes)) - node.AttrCount = uint16(len(attrs)) - a.doc.Attributes = append(a.doc.Attributes, attrs...) - a.pendingAttr = a.pendingAttr[:0] -} - -func (a *Assembler) handleDefinitionListItem(idx int32) { - firstIdx := a.doc.Nodes[idx].Child - if firstIdx != -1 && a.doc.Nodes[firstIdx].Type == NodePara { - termIdx := firstIdx - a.doc.Nodes[termIdx].Type = NodeTerm - - defIdx := a.addNode(NodeDefinition, a.doc.Nodes[termIdx].End, a.doc.Nodes[idx].End) - a.doc.Nodes[defIdx].Child = a.doc.Nodes[termIdx].Next - a.doc.Nodes[termIdx].Next = defIdx - } else { - termIdx := a.addNode(NodeTerm, a.doc.Nodes[idx].Start, a.doc.Nodes[idx].Start) - defIdx := a.addNode(NodeDefinition, a.doc.Nodes[idx].Start, a.doc.Nodes[idx].End) - a.doc.Nodes[defIdx].Child = firstIdx - a.doc.Nodes[idx].Child = termIdx - a.doc.Nodes[termIdx].Next = defIdx - } -} - -func (a *Assembler) isInline(t NodeType) bool { - switch t { - case NodeStr, NodeEmph, NodeStrong, NodeLink, NodeImage, NodeSpan, NodeVerbatim, NodeSubscript, NodeSuperscript, NodeInsert, NodeDelete, NodeMark, NodeDoubleQuoted, NodeSingleQuoted, NodeSmartPunctuation, NodeSoftBreak, NodeHardBreak, NodeInlineMath, NodeDisplayMath, NodeSymb, NodeUrl, NodeEmail, NodeFootnoteReference: - return true - } - return false -} - -func (a *Assembler) addNode(ntype NodeType, start, end int32) int32 { - idx := int32(len(a.doc.Nodes)) - a.doc.Nodes = append(a.doc.Nodes, Node{ - Type: ntype, - Start: start, - End: end, - Child: -1, - Next: -1, - Attr: -1, - }) - return idx -} - -func (a *Assembler) linkToParent(parentIdx, nodeIdx int32) { - if parentIdx == -1 || nodeIdx == -1 || parentIdx == nodeIdx { - return - } - parent := &a.doc.Nodes[parentIdx] - if parent.Child == -1 { - parent.Child = nodeIdx - } else { - curr := parent.Child - if curr == nodeIdx { - return - } - for a.doc.Nodes[curr].Next != -1 { - if a.doc.Nodes[curr].Next == nodeIdx { - return - } - curr = a.doc.Nodes[curr].Next - } - a.doc.Nodes[curr].Next = nodeIdx - } -} - -func (a *Assembler) openNode(ntype NodeType, start int32) int32 { - var parentIdx int32 = -1 - if len(a.stack) > 0 { - parentIdx = a.stack[len(a.stack)-1] - } - nodeIdx := a.addNode(ntype, start, -1) - a.linkToParent(parentIdx, nodeIdx) - a.stack = append(a.stack, nodeIdx) - a.lastClosedNode = -1 - - if ntype == NodeTable { - a.currentTableAlignments = nil - } - return nodeIdx -} - -func (a *Assembler) closeNode(end int32) int32 { - if len(a.stack) <= 1 { - return -1 - } - nodeIdx := a.stack[len(a.stack)-1] - node := &a.doc.Nodes[nodeIdx] - if node.Type != NodeCodeBlock && node.Type != NodeRawBlock && node.Type != NodeDiv { - node.End = end - } - a.stack = a.stack[:len(a.stack)-1] - if a.isInline(a.doc.Nodes[nodeIdx].Type) { - a.lastClosedNode = nodeIdx - } - return nodeIdx -} - -func (a *Assembler) addLeafNode(ntype NodeType, start, end int32) { - parentIdx := a.stack[len(a.stack)-1] - - if ntype == NodeStr && a.lastClosedNode != -1 { - prevNode := &a.doc.Nodes[a.lastClosedNode] - if prevNode.Type == NodeStr && prevNode.End+1 == start { - prevNode.End = end - return - } - } - - nodeIdx := a.addNode(ntype, start, end) - a.linkToParent(parentIdx, nodeIdx) - a.lastClosedNode = nodeIdx -} - -func isOrderedMarker(marker byte) bool { - switch marker { - case '1', 'a', 'A', 'i', 'I': - return true - } - return false -} - -func (a *Assembler) setStyleFromMarker(idx int32, marker byte) { - node := &a.doc.Nodes[idx] - switch marker { - case '1': - node.Data |= DataListDecimal - case 'a': - node.Data |= DataListLowerAlpha - case 'A': - node.Data |= DataListUpperAlpha - case 'i': - node.Data |= DataListLowerRoman - case 'I': - node.Data |= DataListUpperRoman - } -} diff --git a/scripts/mkman/djot/ast.go b/scripts/mkman/djot/ast.go @@ -1,250 +0,0 @@ -package djot - -type NodeType uint16 - -const ( - NodeDoc NodeType = iota - NodeSection - NodePara - NodeHeading - NodeThematicBreak - NodeDiv - NodeCodeBlock - NodeRawBlock - NodeBlockQuote - NodeOrderedList - NodeBulletList - NodeTaskList - NodeDefinitionList - NodeTable - NodeCaption - NodeRow - NodeCell - NodeListItem - NodeTaskListItem - NodeDefinitionListItem - NodeTerm - NodeDefinition - NodeFootnote - NodeReference - - NodeStr - NodeSoftBreak - NodeHardBreak - NodeNonBreakingSpace - NodeSymb - NodeVerbatim - NodeRawInline - NodeInlineMath - NodeDisplayMath - NodeUrl - NodeEmail - NodeFootnoteReference - NodeSmartPunctuation - NodeEmph - NodeStrong - NodeLink - NodeImage - NodeSpan - NodeMark - NodeSuperscript - NodeSubscript - NodeInsert - NodeDelete - NodeDoubleQuoted - NodeSingleQuoted -) - -type Node struct { - Type NodeType - Start, End int32 - Child int32 - Next int32 - Attr int32 - AttrCount uint16 - Level int16 - Data uint32 -} - -type Attribute struct { - KeyStart, KeyEnd int32 - ValStart, ValEnd int32 -} - -const ( - AttrKeyID = -1 - AttrKeyClass = -2 - AttrKeyFormat = -3 -) - -type EventType uint16 - -const ( - EvNone EventType = iota - EvStr - EvSoftBreak - EvHardBreak - EvNonBreakingSpace - EvEscape - EvSymb - EvFootnoteReference - EvSmartPunctuation - EvOpenVerbatim - EvCloseVerbatim - EvRawInline - EvInlineMath - EvDisplayMath - EvUrl - EvEmail - - EvOpenAttributes - EvOpenInlineAttributes - EvCloseAttributes - EvAttrIdMarker - EvAttrClassMarker - EvAttrKey - EvAttrValue - EvAttrEqualMarker - EvAttrQuoteMarker - EvAttrSpace - EvComment - - EvText - - EvOpenPara - EvClosePara - EvOpenHeading - EvCloseHeading - EvOpenBlockQuote - EvCloseBlockQuote - EvOpenList - EvCloseList - EvOpenListItem - EvCloseListItem - EvOpenDiv - EvCloseDiv - EvOpenCodeBlock - EvCloseCodeBlock - EvOpenRawBlock - EvCloseRawBlock - EvOpenTable - EvCloseTable - EvOpenRow - EvCloseRow - EvOpenCell - EvCloseCell - EvOpenCaption - EvCloseCaption - EvOpenFootnote - EvCloseFootnote - EvOpenReferenceDefinition - EvCloseReferenceDefinition - - EvOpenEmph - EvCloseEmph - EvOpenStrong - EvCloseStrong - EvOpenLinkText - EvCloseLinkText - EvOpenImageText - EvCloseImageText - EvOpenDestination - EvCloseDestination - EvOpenReference - EvCloseReference - EvOpenSpan - EvCloseSpan - EvOpenMark - EvCloseMark - EvOpenInsert - EvCloseInsert - EvOpenDelete - EvCloseDelete - EvOpenSuperscript - EvCloseSuperscript - EvOpenSubscript - EvCloseSubscript - EvOpenDoubleQuoted - EvCloseDoubleQuoted - EvOpenSingleQuoted - EvCloseSingleQuoted - - EvBlankLine - EvThematicBreak -) - -type Event struct { - Start, End int32 - Type EventType -} - -type Reference struct { - LabelStart, LabelEnd int32 - DestStart, DestEnd int32 - Attributes []Attribute -} - -type Document struct { - Source []byte - Extra []byte - Nodes []Node - Attributes []Attribute - References map[string]Reference - UsedFootnotes []string - FootnoteContent map[string]int32 - Events []Event -} - -type ContainerType uint8 - -const ( - ContainerNone ContainerType = iota - ContainerDoc - ContainerBlockQuote - ContainerListItem - ContainerList - ContainerPara - ContainerHeading - ContainerTable - ContainerCaption - ContainerFootnote - ContainerDiv - ContainerCodeBlock - ContainerRawBlock - ContainerReferenceDef - ContainerThematicBreak -) - -type ContainerData struct { - Level int16 - Marker byte - MarkerEnd byte - Ordered bool - Tight bool - BlankLines bool - Indent int32 - MarkerWidth int32 - FenceChar byte - FenceLen int32 - IsTask bool - Checked bool - NextNumber int - MarkerAmbiguous bool - MarkerFirstChar byte - OpenListEventIdx int32 -} - -const ( - DataAlignLeft uint32 = 1 << iota - DataAlignCenter - DataAlignRight - DataListTight - DataListDecimal - DataListLowerAlpha - DataListUpperAlpha - DataListLowerRoman - DataListUpperRoman - DataTaskChecked - DataCellHeader - DataNoAutoID -) diff --git a/scripts/mkman/djot/attr.go b/scripts/mkman/djot/attr.go @@ -1,154 +0,0 @@ -package djot - -func isKeyStartChar(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == '-' || b == ':' -} - -func isKeyChar(b byte) bool { - return isKeyStartChar(b) || (b >= '0' && b <= '9') -} - -func isIDChar(b byte) bool { - return isKeyChar(b) -} - -func isSpace(b byte) bool { - return b == ' ' || b == '\t' || b == '\r' || b == '\n' -} - -func ParseAttributes(source []byte, start, end int32) ([]Event, int32, bool) { - if start >= end || source[start] != '{' { - return nil, start, false - } - - pos := start + 1 - var events []Event - - for pos < end { - b := source[pos] - if isSpace(b) { - pos++ - continue - } - - if b == '}' { - return events, pos, true - } - - if b == '#' { - pos++ - idStart := pos - for pos < end && isIDChar(source[pos]) { - pos++ - } - if pos == idStart { - return nil, start, false - } - events = append(events, Event{Start: idStart, End: pos - 1, Type: EvAttrIdMarker}) - continue - } - - if b == '.' { - pos++ - classStart := pos - for pos < end && isKeyChar(source[pos]) { - pos++ - } - if pos == classStart { - return nil, start, false - } - events = append(events, Event{Start: classStart, End: pos - 1, Type: EvAttrClassMarker}) - continue - } - - if b == '%' { - pos++ - commentStart := pos - for pos < end && source[pos] != '%' && source[pos] != '}' { - pos++ - } - if pos < end && source[pos] == '%' { - events = append(events, Event{Start: commentStart, End: pos - 1, Type: EvComment}) - pos++ - } - continue - } - - if b == '=' { - eqPos := pos - pos++ - keyStart := pos - for pos < end && source[pos] != '}' && !isSpace(source[pos]) { - pos++ - } - keyEnd := pos - 1 - if keyEnd >= keyStart { - events = append(events, Event{Type: EvAttrKey, Start: eqPos, End: keyEnd}) - } - continue - } - - if isKeyStartChar(b) { - keyStart := pos - for pos < end && isKeyChar(source[pos]) { - pos++ - } - keyEnd := pos - 1 - - for pos < end && isSpace(source[pos]) { - pos++ - } - - if pos < end && source[pos] == '=' { - events = append(events, Event{Start: keyStart, End: keyEnd, Type: EvAttrKey}) - events = append(events, Event{Start: pos, End: pos, Type: EvAttrEqualMarker}) - pos++ - - for pos < end && isSpace(source[pos]) { - pos++ - } - - if pos < end && source[pos] == '"' { - events = append(events, Event{Start: pos, End: pos, Type: EvAttrQuoteMarker}) - pos++ - valStart := pos - valEnd := valStart - for pos < end { - if source[pos] == '\\' && pos+1 < end { - pos += 2 - } else if source[pos] == '"' { - valEnd = pos - break - } else { - pos++ - } - } - - if pos < end && source[pos] == '"' { - events = append(events, Event{Start: valStart, End: valEnd - 1, Type: EvAttrValue}) - events = append(events, Event{Start: pos, End: pos, Type: EvAttrQuoteMarker}) - pos++ - } else { - return nil, start, false - } - } else { - valStart := pos - for pos < end && isKeyChar(source[pos]) { - pos++ - } - if pos == valStart { - return nil, start, false - } - events = append(events, Event{Start: valStart, End: pos - 1, Type: EvAttrValue}) - } - } else { - return nil, start, false - } - continue - } - - return nil, start, false - } - - return nil, start, false -} diff --git a/scripts/mkman/djot/block.go b/scripts/mkman/djot/block.go @@ -1,1224 +0,0 @@ -package djot - -import ( - "bytes" -) - -type ActiveContainer struct { - Type ContainerType - Start int32 - End int32 - Data ContainerData -} -type BlockParser struct { - source []byte - pos int32 - events []Event - stack []ActiveContainer - - inPara bool - paraLines [][2]int32 - - pendingAttr []Event - hasAttr bool - - inAttrBlock bool - attrLines [][2]int32 - lineIndent int32 - afterBlankLine bool -} - -func NewBlockParser(source []byte) *BlockParser { - p := &BlockParser{ - source: source, - events: make([]Event, 0, len(source)/8+32), - stack: make([]ActiveContainer, 0, 16), - paraLines: make([][2]int32, 0, 8), - attrLines: make([][2]int32, 0, 2), - afterBlankLine: true, - } - p.stack = append(p.stack, ActiveContainer{Type: ContainerDoc}) - return p -} - -func (p *BlockParser) addEvent(start, end int32, etype EventType) { - p.events = append(p.events, Event{Start: start, End: end, Type: etype}) -} - -func (p *BlockParser) Parse() []Event { - for p.pos < int32(len(p.source)) { - lineStart := p.pos - eol := bytes.IndexByte(p.source[p.pos:], '\n') - var nextPos int32 - if eol == -1 { - nextPos = int32(len(p.source)) - } else { - nextPos = p.pos + int32(eol) + 1 - } - - p.handleLine(lineStart, nextPos) - p.pos = nextPos - } - - p.closePara() - p.flushFailedAttr() - p.closePara() - p.discardDanglingAttr() - for i := len(p.stack) - 1; i > 0; i-- { - p.closeContainer(i) - } - return p.events -} - -func (p *BlockParser) handleLine(start, end int32) { - contentEnd := end - if contentEnd > start && p.source[contentEnd-1] == '\n' { - contentEnd-- - if contentEnd > start && p.source[contentEnd-1] == '\r' { - contentEnd-- - } - } - - p.lineIndent = 0 - for start+p.lineIndent < contentEnd && p.source[start+p.lineIndent] == ' ' { - p.lineIndent++ - } - - matched := 1 - currentPos := start - allMatched := true - tipIdx := len(p.stack) - 1 - - for i := 1; i < len(p.stack); i++ { - c := &p.stack[i] - if i == tipIdx && (c.Type == ContainerCodeBlock || c.Type == ContainerRawBlock) { - if p.isClosingFence(c, currentPos, contentEnd) { - p.closePara() - p.closeContainer(i) - return - } - p.closePara() - p.handleLeafContent(c, currentPos, end) - return - } - - tipIsCode := p.stack[tipIdx].Type == ContainerCodeBlock || - p.stack[tipIdx].Type == ContainerRawBlock - if !tipIsCode && c.Type == ContainerDiv { - if p.isClosingFence(c, currentPos, contentEnd) { - p.closePara() - for j := len(p.stack) - 1; j >= i; j-- { - p.closeContainer(j) - } - return - } - } - - if c.Type == ContainerCodeBlock || c.Type == ContainerRawBlock { - break - } - - newPos := p.checkContinue(c, currentPos, contentEnd) - if newPos != -1 { - matched++ - currentPos = newPos - if isLeaf(c.Type) { - break - } - } else { - allMatched = false - break - } - } - isBlank := isBlankLine(p.source, currentPos, contentEnd) - - if isBlank { - p.closePara() - p.discardDanglingAttr() - for i := len(p.stack) - 1; i >= matched; i-- { - p.closeContainer(i) - } - if p.inAttrBlock { - p.flushFailedAttr() - } - p.addEvent(start, end, EvBlankLine) - p.markListBlankLines(matched) - p.afterBlankLine = true - return - } - - defer func() { p.afterBlankLine = false }() - - if p.inAttrBlock { - p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd}) - p.tryParseBufferedAttr() - return - } - - if allMatched && !p.inAttrBlock && currentPos < contentEnd && p.source[currentPos] == '{' && (p.afterBlankLine || p.hasAttr) { - p.inAttrBlock = true - p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd}) - p.tryParseBufferedAttr() - return - } - - newStarts := false - if !allMatched || p.inPara || !isLeaf(p.stack[len(p.stack)-1].Type) { - openPos := currentPos - if openPos < start+p.lineIndent { - openPos = start + p.lineIndent - } - for { - for i := 0; i < 3 && openPos < contentEnd && p.source[openPos] == ' '; i++ { - openPos++ - } - - ctype, nextOpenPos, data, ok := p.findOpen(start, openPos, contentEnd) - if !ok { - break - } - - if p.inPara && !p.canInterrupt(ctype, openPos, contentEnd) { - break - } - - newStarts = true - canHaveImmediateAttr := ctype == ContainerDiv || ctype == ContainerCodeBlock || ctype == ContainerRawBlock || ctype == ContainerHeading - attrPos := nextOpenPos - for attrPos < contentEnd && (p.source[attrPos] == ' ' || p.source[attrPos] == '\t') { - attrPos++ - } - if attrPos < contentEnd && canHaveImmediateAttr { - if p.source[attrPos] == '{' { - attrEvents, nextPos, ok := ParseAttributes(p.source, attrPos, contentEnd) - if ok && isBlankLine(p.source, nextPos+1, contentEnd) { - p.hasAttr = true - p.pendingAttr = append(p.pendingAttr, attrEvents...) - p.closePara() - for i := len(p.stack) - 1; i >= matched; i-- { - p.closeContainer(i) - } - p.openContainer(ctype, openPos, data) - return - } - } else if ctype == ContainerDiv || ctype == ContainerCodeBlock || ctype == ContainerRawBlock { - classStart := attrPos - if ctype == ContainerDiv && p.source[classStart] == '.' { - classStart++ - } - classEnd := classStart - for classEnd < contentEnd && !isSpace(p.source[classEnd]) { - classEnd++ - } - if classEnd > classStart { - p.hasAttr = true - if ctype == ContainerRawBlock { - eqPos := attrPos - 1 - p.pendingAttr = append(p.pendingAttr, Event{Start: eqPos, End: classEnd - 1, Type: EvAttrKey}) - } else if ctype == ContainerCodeBlock && p.source[classStart] == '=' { - ctype = ContainerRawBlock - p.pendingAttr = append(p.pendingAttr, Event{Start: classStart, End: classEnd - 1, Type: EvAttrKey}) - } else { - p.pendingAttr = append(p.pendingAttr, Event{Start: classStart, End: classEnd - 1, Type: EvAttrClassMarker}) - } - nextAttrPos := classEnd - for nextAttrPos < contentEnd && isSpace(p.source[nextAttrPos]) { - nextAttrPos++ - } - if nextAttrPos < contentEnd && p.source[nextAttrPos] == '{' { - attrEvents, _, ok := ParseAttributes(p.source, nextAttrPos, contentEnd) - if ok { - p.pendingAttr = append(p.pendingAttr, attrEvents...) - } - } - p.closePara() - for i := len(p.stack) - 1; i >= matched; i-- { - p.closeContainer(i) - } - p.openContainer(ctype, openPos, data) - return - } - } - } - - p.closePara() - for i := len(p.stack) - 1; i >= matched; i-- { - c := &p.stack[i] - if c.Data.BlankLines && c.Type == ContainerListItem { - c.Data.Tight = false - if i > 0 && p.stack[i-1].Type == ContainerList { - p.stack[i-1].Data.Tight = false - } - } - p.closeContainer(i) - } - p.openContainer(ctype, openPos, data) - - currentPos = nextOpenPos - openPos = nextOpenPos - matched = len(p.stack) - - if currentPos < contentEnd && p.source[currentPos] == '{' && !p.inAttrBlock { - p.inAttrBlock = true - p.attrLines = append(p.attrLines, [2]int32{currentPos, contentEnd}) - p.tryParseBufferedAttr() - return - } - - if isLeaf(ctype) { - if ctype == ContainerReferenceDef { - currentPos = openPos - } - break - } - } - } - - isLazy := !isBlank && !newStarts && matched < len(p.stack) && p.inPara - - if !isLazy { - if matched < len(p.stack) { - p.closePara() - for i := len(p.stack) - 1; i >= matched; i-- { - p.closeContainer(i) - } - } - } - - tipIdx = len(p.stack) - 1 - tip := &p.stack[tipIdx] - - if tip.Type == ContainerTable { - p.handleTableRow(currentPos, contentEnd) - return - } - - if isBlankLine(p.source, currentPos, contentEnd) { - return - } - - if hasInlineContent(tip.Type) || isBlock(tip.Type) || p.inPara { - for currentPos < contentEnd && (p.source[currentPos] == ' ' || p.source[currentPos] == '\t') { - currentPos++ - } - p.accumulateInlineLine(currentPos, contentEnd) - } else { - p.handleLeafContent(tip, currentPos, end) - } -} - -func isBlock(t ContainerType) bool { - switch t { - case ContainerDoc, ContainerBlockQuote, ContainerListItem, ContainerList, ContainerDiv, ContainerFootnote: - return true - } - return false -} - -func hasInlineContent(t ContainerType) bool { - switch t { - case ContainerPara, ContainerHeading, ContainerCaption: - return true - } - return false -} - -func (p *BlockParser) accumulateInlineLine(start, end int32) { - tipIdx := len(p.stack) - 1 - tip := &p.stack[tipIdx] - if (tip.Type == ContainerPara || isBlock(tip.Type)) && !p.inPara { - p.inPara = true - if p.hasAttr { - p.addEvent(start, start, EvOpenAttributes) - p.events = append(p.events, p.pendingAttr...) - p.addEvent(start, start, EvCloseAttributes) - p.hasAttr = false - p.pendingAttr = p.pendingAttr[:0] - } - p.addEvent(start, start, EvOpenPara) - } - p.paraLines = append(p.paraLines, [2]int32{start, end}) -} - -func (p *BlockParser) tryParseBufferedAttr() { - if len(p.attrLines) == 0 { - return - } - - start := p.attrLines[0][0] - end := p.attrLines[len(p.attrLines)-1][1] - - attrEvents, nextPos, ok := ParseAttributes(p.source, start, end) - - if ok { - if isBlankLine(p.source, nextPos+1, end) { - p.closePara() - p.hasAttr = true - p.pendingAttr = append(p.pendingAttr, attrEvents...) - p.inAttrBlock = false - p.attrLines = p.attrLines[:0] - return - } else { - p.flushFailedAttr() - return - } - } else { - hasClosing := false - for i := start; i < end; i++ { - if p.source[i] == '}' { - hasClosing = true - break - } - } - if hasClosing { - p.flushFailedAttr() - } - } -} -func (p *BlockParser) flushFailedAttr() { - p.inAttrBlock = false - for _, line := range p.attrLines { - start := line[0] - for start < line[1] && (p.source[start] == ' ' || p.source[start] == '\t') { - start++ - } - p.accumulateInlineLine(start, line[1]) - } - p.attrLines = p.attrLines[:0] -} - -func (p *BlockParser) closePara() { - if !p.inPara { - if len(p.paraLines) > 0 { - for i, line := range p.paraLines { - start := line[0] - end := line[1] - if i == len(p.paraLines)-1 { - for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') { - end-- - } - } - isHardBreak := false - if i < len(p.paraLines)-1 { - tempEnd := end - for tempEnd > start && (p.source[tempEnd-1] == ' ' || p.source[tempEnd-1] == '\t') { - tempEnd-- - } - if tempEnd > start && p.source[tempEnd-1] == '\\' { - backslashCount := 0 - for j := tempEnd - 1; j >= start && p.source[j] == '\\'; j-- { - backslashCount++ - } - if backslashCount%2 != 0 { - isHardBreak = true - end = tempEnd - 1 - for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') { - end-- - } - } - } - } - if start < end { - p.addEvent(start, end-1, EvText) - } - if i < len(p.paraLines)-1 { - if isHardBreak { - p.addEvent(line[1], line[1], EvHardBreak) - } else { - p.addEvent(line[1], line[1], EvSoftBreak) - } - } - } - p.paraLines = p.paraLines[:0] - } - return - } - - for i, line := range p.paraLines { - start := line[0] - end := line[1] - if i == len(p.paraLines)-1 { - for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') { - end-- - } - } - isHardBreak := false - if i < len(p.paraLines)-1 { - tempEnd := end - for tempEnd > start && (p.source[tempEnd-1] == ' ' || p.source[tempEnd-1] == '\t') { - tempEnd-- - } - if tempEnd > start && p.source[tempEnd-1] == '\\' { - backslashCount := 0 - for j := tempEnd - 1; j >= start && p.source[j] == '\\'; j-- { - backslashCount++ - } - if backslashCount%2 != 0 { - isHardBreak = true - end = tempEnd - 1 - for end > start && (p.source[end-1] == ' ' || p.source[end-1] == '\t') { - end-- - } - } - } - } - if start < end { - p.addEvent(start, end-1, EvText) - } - if i < len(p.paraLines)-1 { - if isHardBreak { - p.addEvent(line[1], line[1], EvHardBreak) - } else { - p.addEvent(line[1], line[1], EvSoftBreak) - } - } - } - - if len(p.paraLines) > 0 { - lastLine := p.paraLines[len(p.paraLines)-1] - p.addEvent(lastLine[1], lastLine[1], EvClosePara) - } - p.inPara = false - p.paraLines = p.paraLines[:0] -} - -func (p *BlockParser) discardDanglingAttr() { - p.hasAttr = false - p.pendingAttr = p.pendingAttr[:0] -} - -func isLeaf(t ContainerType) bool { - switch t { - case ContainerPara, ContainerHeading, ContainerCodeBlock, ContainerRawBlock, ContainerThematicBreak, ContainerReferenceDef, ContainerCaption, ContainerTable: - return true - } - return false -} - -func isBlankLine(source []byte, start, end int32) bool { - for i := start; i < end; i++ { - if source[i] != ' ' && source[i] != '\t' { - return false - } - } - return true -} - -func (p *BlockParser) markListBlankLines(matched int) { -} - -func (p *BlockParser) checkContinue(c *ActiveContainer, pos, end int32) int32 { - switch c.Type { - case ContainerBlockQuote: - if pos < end && p.source[pos] == '>' { - pos++ - if pos == end { - return pos - } - if p.source[pos] == ' ' { - return pos + 1 - } - return -1 - } - case ContainerHeading: - if isBlankLine(p.source, pos, end) { - return -1 - } - hLevel := int32(0) - for pos+hLevel < end && p.source[pos+hLevel] == '#' { - hLevel++ - } - if hLevel > 0 && hLevel <= 6 && (pos+hLevel == end || p.source[pos+hLevel] == ' ' || p.source[pos+hLevel] == '\t') { - if hLevel == int32(c.Data.Level) { - newPos := pos + hLevel - if newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') { - newPos++ - } - return newPos - } - return -1 - } - return pos - case ContainerCodeBlock, ContainerRawBlock: - if p.isClosingFence(c, pos, end) { - return -1 - } - return pos - case ContainerDiv: - return pos - case ContainerList: - return pos - case ContainerListItem: - if isBlankLine(p.source, pos, end) { - return pos - } - if p.lineIndent > c.Data.Indent { - return pos - } - if p.inPara && !p.afterBlankLine { - markerPos := pos + p.lineIndent - _, _, ok := parseListMarker(p.source, markerPos, end) - if !ok { - return pos - } - } - return -1 - case ContainerTable: - if pos < end && p.source[pos] == '|' { - return pos - } - case ContainerFootnote: - if isBlankLine(p.source, pos, end) { - return pos - } - if p.lineIndent > c.Data.Indent { - return pos - } - return -1 - case ContainerReferenceDef: - if isBlankLine(p.source, pos, end) { - return pos - } - if p.lineIndent > c.Data.Indent { - return pos - } - return -1 - case ContainerCaption: - if isBlankLine(p.source, pos, end) { - return -1 - } - return pos - } - return -1 -} - -func (p *BlockParser) isClosingFence(c *ActiveContainer, pos, end int32) bool { - i := 0 - for i < 3 && pos < end && p.source[pos] == ' ' { - pos++ - i++ - } - - char := c.Data.FenceChar - count := int32(0) - for pos < end && p.source[pos] == char { - count++ - pos++ - } - - if count < c.Data.FenceLen { - return false - } - - for pos < end && (p.source[pos] == ' ' || p.source[pos] == '\t') { - pos++ - } - - return pos == end || p.source[pos] == '\r' || p.source[pos] == '\n' -} - -func (p *BlockParser) findOpen(start, pos, end int32) (ContainerType, int32, ContainerData, bool) { - if pos >= end { - return ContainerNone, pos, ContainerData{}, false - } - b := p.source[pos] - - if isThematicBreak(p.source, pos, end) { - return ContainerThematicBreak, end, ContainerData{}, true - } - - if b == '`' || b == '~' || b == ':' { - count := int32(0) - for i := pos; i < end && p.source[i] == b; i++ { - count++ - } - if count >= 3 { - if b == '`' || b == '~' { - rest := p.source[pos+count : end] - hasInvalid := false - for j := 0; j < len(rest); j++ { - if rest[j] == '{' { - break - } - if rest[j] == b { - c := int32(0) - for j < len(rest) && rest[j] == b { - c++ - j++ - } - if c >= count { - hasInvalid = true - break - } - j-- - continue - } - if rest[j] != ' ' && rest[j] != ' ' { - k := j - for k < len(rest) && rest[k] != ' ' && rest[k] != ' ' && rest[k] != '{' { - if rest[k] == b { - c := int32(0) - for k < len(rest) && rest[k] == b { - c++ - k++ - } - if c >= count { - hasInvalid = true - break - } - continue - } - k++ - } - if hasInvalid { - break - } - for k < len(rest) && (rest[k] == ' ' || rest[k] == ' ') { - k++ - } - if k < len(rest) && rest[k] != '{' { - hasInvalid = true - break - } - j = k - 1 - } - } - if hasInvalid { - return ContainerNone, pos, ContainerData{}, false - } - } - if b == ':' { - return ContainerDiv, pos + count, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true - } - classPos := pos + count - for classPos < end && p.source[classPos] == ' ' { - classPos++ - } - if classPos < end && p.source[classPos] == '=' { - return ContainerRawBlock, classPos + 1, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true - } - return ContainerCodeBlock, pos + count, ContainerData{FenceChar: b, FenceLen: count, Indent: pos - start}, true - } - } - - if b == '#' { - level := int32(0) - for i := pos; i < end && p.source[i] == '#'; i++ { - level++ - } - if level > 0 && level <= 6 && (pos+level == end || p.source[pos+level] == ' ') { - newPos := pos + level - if newPos < end && p.source[newPos] == ' ' { - newPos++ - } - return ContainerHeading, newPos, ContainerData{Level: int16(level)}, true - } - } - - if b == '>' { - newPos := pos + 1 - if newPos == end { - return ContainerBlockQuote, newPos, ContainerData{}, true - } - if p.source[newPos] == ' ' { - return ContainerBlockQuote, newPos + 1, ContainerData{}, true - } - return ContainerNone, pos, ContainerData{}, false - } - - if b == '|' { - pipes := 0 - i := pos - for i < end { - if p.source[i] == '|' { - pipes++ - i++ - } else if p.source[i] == '`' { - count := int32(0) - for i < end && p.source[i] == '`' { - count++ - i++ - } - for i < end { - if p.source[i] == '`' { - c := int32(0) - for i < end && p.source[i] == '`' { - c++ - i++ - } - if c == count { - break - } - } else { - i++ - } - } - } else { - i++ - } - } - if pipes >= 2 { - return ContainerTable, pos, ContainerData{}, true - } - } - - if b == '^' { - if pos+1 < end && p.source[pos+1] == ' ' { - return ContainerCaption, pos + 2, ContainerData{}, true - } - } - - if b == '[' { - if pos+1 < end && p.source[pos+1] == '^' { - for i := pos + 2; i < end; i++ { - if p.source[i] == ']' && i+1 < end && p.source[i+1] == ':' { - newPos := i + 2 - for newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') { - newPos++ - } - return ContainerFootnote, newPos, ContainerData{Indent: p.lineIndent, MarkerWidth: newPos - pos}, true - } - } - } else { - for i := pos + 1; i < end; i++ { - if p.source[i] == ']' && i+1 < end && p.source[i+1] == ':' { - newPos := i + 2 - for newPos < end && (p.source[newPos] == ' ' || p.source[newPos] == '\t') { - newPos++ - } - return ContainerReferenceDef, newPos, ContainerData{Indent: p.lineIndent}, true - } - } - } - } - - newPos, data, ok := parseListMarker(p.source, pos, end) - if ok { - data.Indent = pos - start - if !p.canListMarkerInterrupt(p.lineIndent, data.Marker, p.afterBlankLine) { - return ContainerNone, pos, ContainerData{}, false - } - return ContainerListItem, newPos, data, true - } - - return ContainerNone, pos, ContainerData{}, false -} - -func (p *BlockParser) openContainer(ctype ContainerType, start int32, data ContainerData) { - if p.hasAttr { - p.addEvent(start, start, EvOpenAttributes) - p.events = append(p.events, p.pendingAttr...) - p.addEvent(start, start, EvCloseAttributes) - p.hasAttr = false - p.pendingAttr = p.pendingAttr[:0] - } - - switch ctype { - case ContainerHeading: - p.addEvent(start, start+int32(data.Level)-1, EvOpenHeading) - case ContainerBlockQuote: - p.addEvent(start, start, EvOpenBlockQuote) - case ContainerListItem: - tipIdx := len(p.stack) - 1 - tip := &p.stack[tipIdx] - if tip.Type == ContainerListItem { - pIdx := len(p.stack) - 2 - parent := &p.stack[pIdx] - if parent.Type == ContainerList { - itemIndent := tip.Data.Indent - if data.Indent > itemIndent { - p.openList(start, data) - } else if data.Indent == parent.Data.Indent { - p.closeContainer(tipIdx) - if parent.Data.Marker == data.Marker && parent.Data.MarkerEnd == data.MarkerEnd && parent.Data.Ordered == data.Ordered { - if data.Ordered { - parent.Data.NextNumber++ - } - } else { - p.closeContainer(pIdx) - p.openList(start, data) - } - } else { - p.closeContainer(tipIdx) - p.closeContainer(pIdx) - p.openList(start, data) - } - } else { - p.openList(start, data) - } - } else if tip.Type == ContainerList { - if tip.Data.Marker == data.Marker && tip.Data.MarkerEnd == data.MarkerEnd && tip.Data.Ordered == data.Ordered { - if !data.MarkerAmbiguous { - tip.Data.MarkerAmbiguous = false - } - } else if data.Indent == tip.Data.Indent { - if p.tryNarrowList(tip, data) { - } else { - p.closeContainer(tipIdx) - p.openList(start, data) - } - } else { - p.openList(start, data) - } - } else { - p.openList(start, data) - } - - taskStatus := int32(0) - if data.IsTask { - if data.Checked { - taskStatus = 2 - } else { - taskStatus = 1 - } - } - p.addEvent(start, taskStatus, EvOpenListItem) - case ContainerCodeBlock: - p.addEvent(start, start+data.FenceLen-1, EvOpenCodeBlock) - p.addEvent(start, start, EvNone) - case ContainerRawBlock: - p.addEvent(start, start+data.FenceLen-1, EvOpenRawBlock) - p.addEvent(start, start, EvNone) - case ContainerDiv: - p.addEvent(start, start+data.FenceLen-1, EvOpenDiv) - p.addEvent(start, start, EvNone) - case ContainerThematicBreak: - p.addEvent(start, start, EvThematicBreak) - case ContainerTable: - p.addEvent(start, start, EvOpenTable) - case ContainerCaption: - p.addEvent(start, start, EvOpenCaption) - case ContainerFootnote: - p.addEvent(start, start, EvOpenFootnote) - p.addEvent(start, start+data.MarkerWidth-1, EvStr) - case ContainerReferenceDef: - p.addEvent(start, start, EvOpenReferenceDefinition) - } - p.stack = append(p.stack, ActiveContainer{Type: ctype, Start: start, Data: data}) -} - -func (p *BlockParser) closeContainer(idx int) { - c := p.stack[idx] - switch c.Type { - case ContainerHeading: - p.addEvent(c.Start, c.Start, EvCloseHeading) - case ContainerBlockQuote: - p.addEvent(c.Start, c.Start, EvCloseBlockQuote) - case ContainerListItem: - p.addEvent(c.Start, c.Start, EvCloseListItem) - case ContainerList: - tight := int32(0) - if c.Data.Tight { - tight = 1 - } - p.addEvent(c.Start, tight, EvCloseList) - case ContainerCodeBlock: - p.addEvent(c.Start, c.Start, EvCloseCodeBlock) - case ContainerRawBlock: - p.addEvent(c.Start, c.Start, EvCloseRawBlock) - case ContainerDiv: - p.addEvent(c.Start, c.Start, EvCloseDiv) - case ContainerTable: - p.addEvent(c.Start, c.Start, EvCloseTable) - case ContainerCaption: - p.addEvent(c.Start, c.Start, EvCloseCaption) - case ContainerFootnote: - p.addEvent(c.Start, c.Start, EvCloseFootnote) - case ContainerReferenceDef: - p.addEvent(c.Start, c.Start, EvCloseReferenceDefinition) - } - p.stack = p.stack[:idx] -} - -func (p *BlockParser) handleLeafContent(tip *ActiveContainer, start, end int32) { - contentEnd := end - if contentEnd > start && p.source[contentEnd-1] == '\n' { - contentEnd-- - if contentEnd > start && p.source[contentEnd-1] == '\r' { - contentEnd-- - } - } - - if p.hasAttr { - p.addEvent(start, start, EvOpenAttributes) - p.events = append(p.events, p.pendingAttr...) - p.addEvent(start, start, EvCloseAttributes) - p.hasAttr = false - p.pendingAttr = p.pendingAttr[:0] - } - switch tip.Type { - case ContainerCodeBlock, ContainerRawBlock, ContainerDiv: - if p.isClosingFence(tip, start, end) { - p.closeContainer(len(p.stack) - 1) - return - } - - indentToStrip := tip.Data.Indent - current := start - for indentToStrip > 0 && current < end && p.source[current] == ' ' { - current++ - indentToStrip-- - } - if end < int32(len(p.source)) && p.source[end] == '\n' { - end++ - } else if end < int32(len(p.source)) && p.source[end] == '\r' { - end++ - if end < int32(len(p.source)) && p.source[end] == '\n' { - end++ - } - } - p.addEvent(current, end-1, EvStr) - case ContainerTable: - p.handleTableRow(start, end) - case ContainerHeading, ContainerCaption: - p.accumulateInlineLine(start, end) - case ContainerReferenceDef: - actualEnd := contentEnd - 1 - if actualEnd >= int32(len(p.source)) { - actualEnd = int32(len(p.source)) - 1 - } - if tip.Start <= actualEnd { - p.addEvent(tip.Start, actualEnd, EvStr) - } - case ContainerFootnote: - actualEnd := contentEnd - 1 - if actualEnd >= int32(len(p.source)) { - actualEnd = int32(len(p.source)) - 1 - } - if actualEnd >= start { - p.addEvent(start, actualEnd, EvStr) - } - } -} - -func (p *BlockParser) handleTableRow(start, end int32) { - isSep := false - hasDash := false - for i := start; i < end; i++ { - b := p.source[i] - if b == '-' || b == ':' { - hasDash = true - } else if b != '|' && b != ' ' && b != '\t' { - hasDash = false - break - } - } - isSep = hasDash - - if isSep { - p.addEvent(start, end, EvStr) - return - } - - p.addEvent(start, start, EvOpenRow) - pos := start - for pos < end { - if p.source[pos] == '|' { - pos++ - if pos >= end { - break - } - cellStart := pos - for pos < end { - if p.source[pos] == '\\' && pos+1 < end { - pos += 2 - } else if p.source[pos] == '`' { - count := int32(0) - for pos < end && p.source[pos] == '`' { - count++ - pos++ - } - for pos < end { - if p.source[pos] == '`' { - c := int32(0) - for pos < end && p.source[pos] == '`' { - c++ - pos++ - } - if c == count { - break - } - } else { - pos++ - } - } - } else if p.source[pos] == '|' { - break - } else { - pos++ - } - } - cellEnd := pos - 1 - for cellStart <= cellEnd && isSpace(p.source[cellStart]) { - cellStart++ - } - for cellEnd >= cellStart && isSpace(p.source[cellEnd]) { - cellEnd-- - } - p.addEvent(cellStart, cellStart, EvOpenCell) - if cellStart <= cellEnd { - p.addEvent(cellStart, cellEnd, EvText) - } - p.addEvent(pos, pos, EvCloseCell) - } else { - pos++ - } - } - p.addEvent(end, end, EvCloseRow) -} - -func (p *BlockParser) canListMarkerInterrupt(markerIndent int32, markerChar byte, afterBlankLine bool) bool { - isDefinition := markerChar == ':' - - for i := len(p.stack) - 1; i >= 0; i-- { - c := p.stack[i] - if c.Type == ContainerList || c.Type == ContainerListItem { - parentMarker := c.Data.Marker - parentIsDefinition := parentMarker == ':' - parentIndent := c.Data.Indent - - if isDefinition == parentIsDefinition { - if !afterBlankLine && markerIndent > parentIndent && markerIndent < parentIndent+4 { - return false - } - } - return true - } - } - return true -} - -func (p *BlockParser) canInterrupt(ctype ContainerType, pos, end int32) bool { - switch ctype { - case ContainerFootnote: - return true - case ContainerListItem: - _, data, ok := parseListMarker(p.source, pos, end) - if !ok { - return false - } - if data.Ordered && data.NextNumber != 1 { - alreadyInOrderedList := false - canNarrowExistingList := false - canContinueAsRoman := false - hasDifferentMarkerList := false - for i := len(p.stack) - 1; i >= 0; i-- { - c := p.stack[i] - if c.Type == ContainerList && c.Data.Ordered && - c.Data.Marker == data.Marker && c.Data.MarkerEnd == data.MarkerEnd && - c.Data.Indent == p.lineIndent { - alreadyInOrderedList = true - break - } - if c.Type == ContainerList && c.Data.Ordered && - c.Data.Indent == p.lineIndent { - if c.Data.Marker != data.Marker || c.Data.MarkerEnd != data.MarkerEnd { - hasDifferentMarkerList = true - } - if c.Data.Marker == 'i' && data.Marker == 'a' && c.Data.MarkerAmbiguous && !isRomanLowerStart(data.MarkerFirstChar) { - canNarrowExistingList = true - break - } - if c.Data.Marker == 'I' && data.Marker == 'A' && c.Data.MarkerAmbiguous && !isRomanUpperStart(data.MarkerFirstChar) { - canNarrowExistingList = true - break - } - if c.Data.Marker == 'i' && data.Marker == 'a' && data.MarkerAmbiguous && isRomanLowerStart(data.MarkerFirstChar) { - if parseRoman([]byte{data.MarkerFirstChar}) == c.Data.NextNumber { - canContinueAsRoman = true - break - } - } - if c.Data.Marker == 'I' && data.Marker == 'A' && data.MarkerAmbiguous && isRomanUpperStart(data.MarkerFirstChar) { - if parseRoman([]byte{data.MarkerFirstChar}) == c.Data.NextNumber { - canContinueAsRoman = true - break - } - } - } - } - if !alreadyInOrderedList && !canNarrowExistingList && !canContinueAsRoman && !hasDifferentMarkerList { - return false - } - } - return p.canListMarkerInterrupt(p.lineIndent, data.Marker, p.afterBlankLine) - } - return false -} -func (p *BlockParser) tryNarrowList(list *ActiveContainer, newItem ContainerData) bool { - lower := list.Data.Marker == 'i' - upper := list.Data.Marker == 'I' - if !lower && !upper { - return false - } - - if lower { - if list.Data.MarkerAmbiguous && newItem.Marker == 'a' && !isRomanLowerStart(newItem.MarkerFirstChar) { - startNum := int(list.Data.MarkerFirstChar - 'a' + 1) - p.events[list.Data.OpenListEventIdx].End = int32('a') - p.events[list.Data.OpenListEventIdx+1].End = int32(startNum) - list.Data.Marker = 'a' - list.Data.MarkerAmbiguous = false - return true - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && !isRomanLowerStart(newItem.MarkerFirstChar) { - return false - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && isRomanLowerStart(newItem.MarkerFirstChar) { - if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'i' && newItem.MarkerAmbiguous { - if newItem.NextNumber == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'a' && newItem.MarkerAmbiguous && isRomanLowerStart(newItem.MarkerFirstChar) { - if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - } - - if upper { - if list.Data.MarkerAmbiguous && newItem.Marker == 'A' && !isRomanUpperStart(newItem.MarkerFirstChar) { - startNum := int(list.Data.MarkerFirstChar - 'A' + 1) - p.events[list.Data.OpenListEventIdx].End = int32('A') - p.events[list.Data.OpenListEventIdx+1].End = int32(startNum) - list.Data.Marker = 'A' - list.Data.MarkerAmbiguous = false - return true - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'A' && isRomanUpperStart(newItem.MarkerFirstChar) { - if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'I' && newItem.MarkerAmbiguous { - if newItem.NextNumber == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - if !list.Data.MarkerAmbiguous && newItem.Marker == 'A' && newItem.MarkerAmbiguous && isRomanUpperStart(newItem.MarkerFirstChar) { - if parseRoman([]byte{newItem.MarkerFirstChar}) == list.Data.NextNumber { - list.Data.NextNumber++ - return true - } - } - } - return false -} - -func (p *BlockParser) openList(start int32, data ContainerData) { - data.OpenListEventIdx = int32(len(p.events)) - p.addEvent(start, int32(data.Marker), EvOpenList) - p.addEvent(start, int32(data.NextNumber), EvNone) - p.stack = append(p.stack, ActiveContainer{Type: ContainerList, Start: start, Data: data}) - p.stack[len(p.stack)-1].Data.NextNumber++ -} diff --git a/scripts/mkman/djot/inline.go b/scripts/mkman/djot/inline.go @@ -1,918 +0,0 @@ -package djot - -type Opener struct { - MatchIndex int32 - Start int32 - Type EventType - Char byte - Explicit bool -} - -type InlineParser struct { - source []byte - events []Event - stack []Opener -} - -func NewInlineParser(source []byte) *InlineParser { - return &InlineParser{ - source: source, - events: make([]Event, 0, 256), - stack: make([]Opener, 0, 16), - } -} - -func (p *InlineParser) Reset() { - p.stack = p.stack[:0] -} - -func (p *InlineParser) Parse(blockEvents []Event) []Event { - var textEvents []Event - for i := 0; i < len(blockEvents); i++ { - ev := blockEvents[i] - if ev.Type == EvText || ev.Type == EvSoftBreak || ev.Type == EvHardBreak { - textEvents = append(textEvents, ev) - } else { - if len(textEvents) > 0 { - p.parseInlineBlock(textEvents) - textEvents = textEvents[:0] - } - if ev.Type == EvClosePara || ev.Type == EvCloseHeading || ev.Type == EvCloseCaption || ev.Type == EvCloseListItem || ev.Type == EvCloseCell { - p.Trim() - } - p.events = append(p.events, ev) - p.Reset() - } - } - if len(textEvents) > 0 { - p.parseInlineBlock(textEvents) - } - - return p.events -} - -func (p *InlineParser) Trim() { - if len(p.events) == 0 { - return - } - i := len(p.events) - 1 - if p.events[i].Type == EvSoftBreak || p.events[i].Type == EvHardBreak { - p.events = p.events[:i] - i-- - if i >= 0 && p.events[i].Type == EvStr { - end := p.events[i].End - start := p.events[i].Start - for end >= start && (p.source[end] == ' ' || p.source[end] == '\t') { - end-- - } - if end < start { - p.events = p.events[:i] - } else { - p.events[i].End = end - } - } - } -} - -func (p *InlineParser) findNextSpecialAhead(pos int32, end int32) int32 { - for i := pos; i <= end; i++ { - if isSpecial(p.source[i]) || p.source[i] == '{' { - return i - } - } - return end + 1 -} - -func (p *InlineParser) parseInlineBlock(textEvents []Event) { - if len(textEvents) == 0 { - return - } - - blockEnd := textEvents[len(textEvents)-1].End - - evIdx := 0 - for evIdx < len(textEvents) { - ev := textEvents[evIdx] - if ev.Type == EvSoftBreak { - p.addEvent(ev.Start, ev.End, EvSoftBreak) - evIdx++ - continue - } - if ev.Type == EvHardBreak { - p.addEvent(ev.Start, ev.End, EvHardBreak) - evIdx++ - continue - } - - start := ev.Start - end := ev.End - pos := start - - for pos <= end { - if pos >= int32(len(p.source)) { - break - } - - b := p.source[pos] - - if !isSpecial(b) && b != '{' { - next := p.findNextSpecialAhead(pos+1, end) - p.addEvent(pos, next-1, EvStr) - pos = next - continue - } - - if b == '{' { - if pos+1 <= end { - next := p.source[pos+1] - if next == '_' || next == '*' || next == '~' || next == '^' || next == '-' || next == '+' || next == '=' || next == '\'' || next == '"' { - p.addEvent(pos, pos, EvOpenInlineAttributes) - newPos := p.handleEmphasis(next, pos+1, end) - pos = newPos - continue - } - } - - attrEvents, nextPos, ok := ParseAttributes(p.source, pos, blockEnd+1) - if ok { - p.handleAttributeAttachment(pos, nextPos, attrEvents) - pos = nextPos + 1 - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - continue - } else { - p.addEvent(pos, pos, EvStr) - pos++ - continue - } - } - - switch b { - case '\\': - if pos+1 <= end { - next := p.source[pos+1] - if next == ' ' { - p.addEvent(pos, pos+1, EvNonBreakingSpace) - pos += 2 - } else if isPunctuation(next) { - p.addEvent(pos, pos+1, EvEscape) - pos += 2 - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - case '*': - pos = p.handleEmphasis(b, pos, end) - case '_': - pos = p.handleEmphasis(b, pos, end) - case '^': - pos = p.handleEmphasis(b, pos, end) - case '~': - pos = p.handleEmphasis(b, pos, end) - case '"': - p.handleDoubleQuote(pos, end) - pos++ - case '\'': - pos = p.handleSingleQuote(pos, end) - case '[': - if pos+1 <= blockEnd && p.source[pos+1] == '^' { - closeIdx := p.findClosingBracketAhead(pos, textEvents, evIdx) - if closeIdx != -1 { - p.addEvent(pos, closeIdx, EvFootnoteReference) - pos = closeIdx + 1 - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - continue - } - } - p.addOpener(b, pos, EvOpenLinkText, false) - pos++ - case '!': - if pos+1 <= end && p.source[pos+1] == '[' { - p.addOpener('[', pos+1, EvOpenImageText, false) - pos += 2 - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - case ']': - pos = p.handleCloseBracketAhead(pos, textEvents, evIdx, blockEnd) - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - case '(': - if len(p.events) > 0 && p.events[len(p.events)-1].Type == EvCloseLinkText { - destEnd := p.findClosingParenAhead(pos+1, textEvents, evIdx) - if destEnd != -1 { - p.addEvent(pos+1, destEnd-1, EvOpenDestination) - p.addEvent(pos+1, destEnd-1, EvCloseDestination) - pos = destEnd + 1 - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - continue - } - } - p.addEvent(pos, pos, EvStr) - pos++ - case '`': - pos = p.handleVerbatimAhead(pos, textEvents, evIdx) - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - - if pos < blockEnd && p.source[pos] == '{' { - attrEvents, nextPos, ok := ParseAttributes(p.source, pos, blockEnd+1) - if ok { - isRaw := false - if len(attrEvents) == 1 { - ae := attrEvents[0] - if ae.Type == EvAttrKey && p.source[ae.Start] == '=' { - isRaw = true - } - } - - if isRaw { - p.events[len(p.events)-2].Type = EvRawInline - p.events[len(p.events)-1].Type = EvRawInline - p.handleAttributeAttachment(pos, nextPos, attrEvents) - pos = nextPos + 1 - } - - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - } - } - case '.': - if pos+2 <= end && p.source[pos+1] == '.' && p.source[pos+2] == '.' { - p.addEvent(pos, pos+2, EvSmartPunctuation) - pos += 3 - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - case '-': - if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') { - pos = p.handleEmphasis(b, pos, end) - continue - } - - count := int32(0) - for pos+count <= end && p.source[pos+count] == '-' { - count++ - } - - if pos+count <= end && p.source[pos+count] == '}' { - if count > 1 { - count-- - } else { - pos = p.handleEmphasis(b, pos, end) - continue - } - } - - if count == 1 { - p.addEvent(pos, pos, EvStr) - pos++ - } else { - emd := int32(0) - end2 := int32(0) - if count%3 == 0 { - emd = count / 3 - end2 = 0 - } else if count%2 == 0 { - emd = 0 - end2 = count / 2 - } else if count%3 == 2 { - emd = count / 3 - end2 = 1 - } else { - emd = (count - 4) / 3 - end2 = 2 - } - p2 := pos - for i := int32(0); i < emd; i++ { - p.addEvent(p2, p2+2, EvSmartPunctuation) - p2 += 3 - } - for i := int32(0); i < end2; i++ { - p.addEvent(p2, p2+1, EvSmartPunctuation) - p2 += 2 - } - pos = p2 - } - case '+': - if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') { - pos = p.handleEmphasis(b, pos, end) - continue - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - case '=': - if (pos > 0 && p.source[pos-1] == '{') || (pos+1 <= end && p.source[pos+1] == '}') { - pos = p.handleEmphasis(b, pos, end) - continue - } else { - p.addEvent(pos, pos, EvStr) - pos++ - } - case '<': - pos = p.handleAutolink(pos, end) - case ':': - pos = p.handleEmoji(pos, end) - case '$': - count := int32(0) - for pos+count <= end && p.source[pos+count] == '$' { - count++ - } - if pos+count <= end && p.source[pos+count] == '`' { - pos = p.handleMathVerbatim(pos, pos+count, end, textEvents, evIdx) - for evIdx < len(textEvents) && pos > textEvents[evIdx].End { - evIdx++ - } - if evIdx < len(textEvents) && pos >= textEvents[evIdx].Start { - end = textEvents[evIdx].End - start = pos - } - } else { - pos = p.handleMath(pos, end) - } - default: - p.addEvent(pos, pos, EvStr) - pos++ - } - start = pos - } - evIdx++ - } - - for _, opener := range p.stack { - if opener.MatchIndex != -1 && (opener.Char == '\'' || opener.Char == '"') { - p.events[opener.MatchIndex].Type = EvSmartPunctuation - } - } -} - -func (p *InlineParser) findClosingParenAhead(start int32, textEvents []Event, startEvIdx int) int32 { - count := 0 - for j := startEvIdx; j < len(textEvents); j++ { - ev := textEvents[j] - if ev.Type == EvSoftBreak { - continue - } - s := ev.Start - if j == startEvIdx { - s = start - } - for i := s; i <= ev.End; i++ { - if p.source[i] == '(' { - count++ - } else if p.source[i] == ')' { - count-- - if count == 0 { - return i - } - } - } - } - return -1 -} - -func (p *InlineParser) findClosingBracketAhead(start int32, textEvents []Event, startEvIdx int) int32 { - count := 0 - for j := startEvIdx; j < len(textEvents); j++ { - ev := textEvents[j] - if ev.Type == EvSoftBreak { - continue - } - s := ev.Start - if j == startEvIdx { - s = start - } - for i := s; i <= ev.End; i++ { - if p.source[i] == '[' { - count++ - } else if p.source[i] == ']' { - count-- - if count == 0 { - return i - } - } - } - } - return -1 -} - -func (p *InlineParser) handleCloseBracketAhead(pos int32, textEvents []Event, evIdx int, blockEnd int32) int32 { - for i := len(p.stack) - 1; i >= 0; i-- { - opener := p.stack[i] - if opener.MatchIndex != -1 && opener.Char == '[' { - next := pos + 1 - if next <= blockEnd && p.source[next] == '(' { - closeIdx := p.findClosingParenAhead(next, textEvents, evIdx) - if closeIdx != -1 { - p.events[opener.MatchIndex].Type = opener.Type - p.addEvent(next+1, closeIdx-1, EvOpenDestination) - p.addEvent(next+1, closeIdx-1, EvCloseDestination) - p.addEvent(pos, pos, closeTypeFor(opener.Type)) - p.stack = p.stack[:i] - return closeIdx + 1 - } - } - - if next <= blockEnd && p.source[next] == '[' { - closeIdx := p.findClosingBracketAhead(next, textEvents, evIdx) - if closeIdx != -1 { - p.events[opener.MatchIndex].Type = opener.Type - p.addEvent(next+1, closeIdx-1, EvOpenReference) - p.addEvent(next+1, closeIdx-1, EvCloseReference) - p.addEvent(pos, pos, closeTypeFor(opener.Type)) - p.stack = p.stack[:i] - return closeIdx + 1 - } - } - - if next <= blockEnd && p.source[next] == '{' { - attrEvents, attrEndPos, ok := ParseAttributes(p.source, next, blockEnd+1) - if ok { - p.events[opener.MatchIndex].Type = EvOpenSpan - p.addEvent(pos, pos, EvCloseSpan) - p.addEvent(next, next, EvOpenInlineAttributes) - p.events = append(p.events, attrEvents...) - p.addEvent(attrEndPos, attrEndPos, EvCloseAttributes) - p.stack = p.stack[:i] - return attrEndPos + 1 - } - } - - p.events[opener.MatchIndex].Type = EvStr - p.addEvent(pos, pos, EvStr) - p.stack = p.stack[:i] - return pos + 1 - } - } - p.addEvent(pos, pos, EvStr) - return pos + 1 -} - -func (p *InlineParser) handleMathVerbatim(dollarPos, backtickPos, end int32, textEvents []Event, startEvIdx int) int32 { - count := int32(0) - pos := backtickPos - ev := textEvents[startEvIdx] - for pos <= ev.End && p.source[pos] == '`' { - count++ - pos++ - } - - contentStart := pos - - for j := startEvIdx; j < len(textEvents); j++ { - tev := textEvents[j] - if tev.Type == EvSoftBreak { - continue - } - - s := tev.Start - if j == startEvIdx { - s = pos - } - - for i := s; i <= tev.End; i++ { - if p.source[i] == '`' { - c := int32(0) - for i+c <= tev.End && p.source[i+c] == '`' { - c++ - } - if c == count { - contentEnd := i - 1 - dollarCount := backtickPos - dollarPos - etype := EvInlineMath - if dollarCount == 2 { - etype = EvDisplayMath - } - p.addEvent(contentStart, contentEnd, etype) - return i + count - } - i += c - 1 - } - } - } - - lastEv := textEvents[len(textEvents)-1] - dollarCount := backtickPos - dollarPos - etype := EvInlineMath - if dollarCount == 2 { - etype = EvDisplayMath - } - p.addEvent(contentStart, lastEv.End, etype) - return lastEv.End + 1 -} - -func (p *InlineParser) handleVerbatimAhead(pos int32, textEvents []Event, startEvIdx int) int32 { - count := int32(0) - - ev := textEvents[startEvIdx] - for pos <= ev.End && p.source[pos] == '`' { - count++ - pos++ - } - - contentStart := pos - - for j := startEvIdx; j < len(textEvents); j++ { - tev := textEvents[j] - if tev.Type == EvSoftBreak { - continue - } - - s := tev.Start - if j == startEvIdx { - s = pos - } - - for i := s; i <= tev.End; i++ { - if p.source[i] == '`' { - c := int32(0) - for i+c <= tev.End && p.source[i+c] == '`' { - c++ - } - if c == count { - contentEnd := i - 1 - - if count == 1 && contentEnd-contentStart+1 >= 2 && p.source[contentStart] == ' ' && p.source[contentEnd] == ' ' { - allSpaces := true - for k := contentStart; k <= contentEnd; k++ { - if p.source[k] != ' ' { - allSpaces = false - break - } - } - if !allSpaces { - contentStart++ - contentEnd-- - } - } - - p.addEvent(contentStart, contentEnd, EvOpenVerbatim) - p.addEvent(contentStart, contentEnd, EvCloseVerbatim) - return i + count - } - i += c - 1 - } - } - } - - lastEv := textEvents[len(textEvents)-1] - p.addEvent(contentStart, lastEv.End, EvOpenVerbatim) - p.addEvent(contentStart, lastEv.End, EvCloseVerbatim) - return lastEv.End + 1 -} - -func (p *InlineParser) handleAttributeAttachment(braceStart, braceEnd int32, attrEvents []Event) { - p.addEvent(braceStart, braceStart, EvOpenInlineAttributes) - p.events = append(p.events, attrEvents...) - p.addEvent(braceEnd, braceEnd, EvCloseAttributes) -} - -func isSpecial(b byte) bool { - switch b { - case '\\', '`', '_', '*', '~', '^', '$', '[', ']', '!', '<', '.', '-', ':', '"', '\'', '+', '=': - return true - } - return false -} - -func closeTypeFor(openType EventType) EventType { - if openType == EvOpenLinkText { - return EvCloseLinkText - } - return EvCloseImageText -} - -func (p *InlineParser) addEvent(start, end int32, etype EventType) int32 { - p.events = append(p.events, Event{Start: start, End: end, Type: etype}) - return int32(len(p.events) - 1) -} - -func (p *InlineParser) addOpener(char byte, pos int32, etype EventType, explicit bool) { - idx := p.addEvent(pos, pos, etype) - p.stack = append(p.stack, Opener{ - MatchIndex: idx, - Start: pos, - Type: etype, - Char: char, - Explicit: explicit, - }) -} - -func (p *InlineParser) handleEmphasis(b byte, pos int32, end int32) int32 { - lastMatch := Event{Type: EvNone} - if len(p.events) > 0 { - lastMatch = p.events[len(p.events)-1] - } - - isExplicitOpen := lastMatch.Type == EvOpenInlineAttributes && lastMatch.Start == pos-1 - isExplicitClose := pos+1 <= end && p.source[pos+1] == '}' - - canOpen := pos+1 <= end && !isSpace(p.source[pos+1]) - canClose := pos-1 >= 0 && !isSpace(p.source[pos-1]) - - if isExplicitOpen { - canOpen = true - canClose = false - } - if isExplicitClose { - canClose = true - canOpen = false - } - - if canClose { - var openerIdx = -1 - for i := len(p.stack) - 1; i >= 0; i-- { - if p.stack[i].MatchIndex != -1 && p.stack[i].Char == b && p.stack[i].Explicit == isExplicitClose && p.stack[i].Type != EvOpenLinkText && p.stack[i].Type != EvOpenImageText { - openerIdx = i - break - } - } - - if openerIdx != -1 { - opener := p.stack[openerIdx] - if opener.Start != pos-1 { - p.handleCloseEmphasisAt(openerIdx, pos, isExplicitClose) - if isExplicitClose { - return pos + 2 - } - return pos + 1 - } - } - } - - if canOpen { - startPos := pos - if isExplicitOpen { - startPos = pos - 1 - p.events = p.events[:len(p.events)-1] - p.addOpener(b, startPos, EvStr, isExplicitOpen) - p.addEvent(pos, pos, EvStr) - } else { - p.addOpener(b, startPos, EvStr, isExplicitOpen) - } - return pos + 1 - } else { - p.addEvent(pos, pos, EvStr) - if isExplicitClose { - p.addEvent(pos+1, pos+1, EvStr) - return pos + 2 - } - return pos + 1 - } -} - -func (p *InlineParser) handleCloseEmphasisAt(openerIdx int, pos int32, explicit bool) { - opener := p.stack[openerIdx] - var b = opener.Char - var openType, closeType EventType - switch b { - case '_': - openType, closeType = EvOpenEmph, EvCloseEmph - case '*': - openType, closeType = EvOpenStrong, EvCloseStrong - case '~': - openType, closeType = EvOpenSubscript, EvCloseSubscript - case '^': - openType, closeType = EvOpenSuperscript, EvCloseSuperscript - case '-': - openType, closeType = EvOpenDelete, EvCloseDelete - case '+': - openType, closeType = EvOpenInsert, EvCloseInsert - case '=': - openType, closeType = EvOpenMark, EvCloseMark - case '\'': - openType, closeType = EvOpenSingleQuoted, EvCloseSingleQuoted - case '"': - openType, closeType = EvOpenDoubleQuoted, EvCloseDoubleQuoted - } - p.events[opener.MatchIndex].Type = openType - p.events[opener.MatchIndex].Start = opener.Start - - if opener.Explicit { - if opener.MatchIndex+1 < int32(len(p.events)) && p.events[opener.MatchIndex+1].Start == opener.Start+1 && p.events[opener.MatchIndex+1].Type == EvStr { - p.events[opener.MatchIndex+1].Type = EvNone - } - } - - endPos := pos - if explicit { - endPos = pos + 1 - } - p.addEvent(pos, endPos, closeType) - - p.clearOpeners(opener.Start, pos) - p.stack = p.stack[:openerIdx] -} - -func (p *InlineParser) clearOpeners(start, end int32) { - for i := range p.stack { - if p.stack[i].Start > start && p.stack[i].Start < end { - if p.stack[i].MatchIndex != -1 { - p.events[p.stack[i].MatchIndex].Type = EvStr - p.stack[i].MatchIndex = -1 - } - } - } -} - -func (p *InlineParser) handleMath(pos, end int32) int32 { - start := pos - pos++ - count := int32(1) - if pos <= end && p.source[pos] == '$' { - count = 2 - pos++ - } - for pos <= end { - if p.source[pos] == '$' { - c := int32(0) - for pos <= end && p.source[pos] == '$' { - c++ - pos++ - } - if c == count { - etype := EvInlineMath - if count == 2 { - etype = EvDisplayMath - } - p.addEvent(start+count, pos-count-1, etype) - return pos - } - } else { - pos++ - } - } - p.addEvent(start, start+count-1, EvStr) - return start + count -} - -func (p *InlineParser) handleAutolink(pos, end int32) int32 { - start := pos - hasAt := false - hasSlash := false - for pos <= end && p.source[pos] != '>' && p.source[pos] != ' ' { - if p.source[pos] == '@' { - hasAt = true - } else if p.source[pos] == '/' { - hasSlash = true - } - pos++ - } - if pos <= end && p.source[pos] == '>' { - etype := EvUrl - if hasAt && !hasSlash { - etype = EvEmail - } - p.addEvent(start+1, pos-1, etype) - return pos + 1 - } - p.addEvent(start, start, EvStr) - return start + 1 -} - -func (p *InlineParser) handleEmoji(pos, end int32) int32 { - start := pos - pos++ - for pos <= end && isAlphaLower(p.source[pos]) { - pos++ - } - if pos <= end && p.source[pos] == ':' { - p.addEvent(start+1, pos-1, EvSymb) - return pos + 1 - } - p.addEvent(start, start, EvStr) - return start + 1 -} - -func (p *InlineParser) handleDoubleQuote(pos, end int32) { - for i := len(p.stack) - 1; i >= 0; i-- { - opener := p.stack[i] - if opener.MatchIndex != -1 && opener.Char == '"' { - p.events[opener.MatchIndex].Type = EvOpenDoubleQuoted - p.addEvent(pos, pos, EvCloseDoubleQuoted) - p.stack = p.stack[:i] - return - } - } - p.addOpener('"', pos, EvStr, false) -} - -func (p *InlineParser) handleSingleQuote(pos, end int32) int32 { - isExplicitClose := pos+1 <= end && p.source[pos+1] == '}' - - if isExplicitClose { - for i := len(p.stack) - 1; i >= 0; i-- { - if p.stack[i].MatchIndex != -1 && p.stack[i].Char == '\'' && p.stack[i].Explicit { - opener := p.stack[i] - p.events[opener.MatchIndex].Type = EvOpenSingleQuoted - p.addEvent(pos, pos, EvCloseSingleQuoted) - if opener.MatchIndex+1 < int32(len(p.events)) && p.events[opener.MatchIndex+1].Start == opener.Start+1 && p.events[opener.MatchIndex+1].Type == EvStr { - p.events[opener.MatchIndex+1].Type = EvNone - } - p.stack = p.stack[:i] - return pos + 2 - } - } - } - - prevIsCloser := pos > 0 && (isAlnum(p.source[pos-1]) || isClosingPunct(p.source[pos-1])) - nextDigit := pos+1 <= end && isDigit(p.source[pos+1]) - - canClose := pos > 0 && !isSpace(p.source[pos-1]) - canOpen := pos+1 <= end && !isSpace(p.source[pos+1]) && - (pos == 0 || isOpeningContext(p.source[pos-1])) - - if prevIsCloser || nextDigit { - for i := len(p.stack) - 1; i >= 0; i-- { - if p.stack[i].MatchIndex != -1 && p.stack[i].Char == '\'' { - p.events[p.stack[i].MatchIndex].Type = EvOpenSingleQuoted - p.addEvent(pos, pos, EvCloseSingleQuoted) - p.stack = p.stack[:i] - return pos + 1 - } - } - p.addEvent(pos, pos, EvSmartPunctuation) - return pos + 1 - } - - if canClose && !canOpen { - for i := len(p.stack) - 1; i >= 0; i-- { - opener := p.stack[i] - if opener.MatchIndex != -1 && opener.Char == '\'' { - p.events[opener.MatchIndex].Type = EvOpenSingleQuoted - p.addEvent(pos, pos, EvCloseSingleQuoted) - p.stack = p.stack[:i] - return pos + 1 - } - } - } - - if canOpen { - p.addOpener('\'', pos, EvStr, false) - } else { - p.addEvent(pos, pos, EvSmartPunctuation) - } - return pos + 1 -} - -func isAlnum(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') -} - -func isClosingPunct(b byte) bool { - return b == ')' || b == ']' || b == '}' || - b == '.' || b == ',' || b == ';' || b == ':' || - b == '!' || b == '?' -} - -func isOpeningContext(b byte) bool { - return b == ' ' || b == '\t' || b == '\n' || b == '\r' || - b == '"' || b == '\'' || b == '-' || b == '(' || b == '[' -} - -func isPunctuation(b byte) bool { - switch b { - case '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~': - return true - } - return false -} diff --git a/scripts/mkman/djot/marker.go b/scripts/mkman/djot/marker.go @@ -1,306 +0,0 @@ -package djot - -func isThematicBreak(source []byte, start, end int32) bool { - count := 0 - for i := start; i < end; i++ { - b := source[i] - if b == '-' || b == '*' { - count++ - } else if b == ' ' || b == '\t' { - continue - } else { - return false - } - } - return count >= 3 -} - -func parseListMarker(source []byte, pos, end int32) (int32, ContainerData, bool) { - if pos >= end { - return pos, ContainerData{}, false - } - - startPos := pos - b := source[pos] - - if b == '-' || b == '+' || b == '*' { - return checkListItemEnd(source, startPos, pos, end, b, false, 0, 0) - } - - if b == ':' { - return checkListItemEnd(source, startPos, pos, end, ':', false, 0, 0) - } - - if isDigit(b) { - p := pos - for p < end && isDigit(source[p]) { - p++ - } - if p < end && (source[p] == '.' || source[p] == ')') { - num := parseDecimal(source[pos:p]) - return checkListItemEnd(source, startPos, p, end, '1', true, num, source[p]) - } - } - - if isRomanLowerStart(b) { - p := pos - for p < end && isRomanLower(source[p]) { - p++ - } - if p < end && (source[p] == '.' || source[p] == ')') { - num := parseRoman(source[pos:p]) - newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'i', true, num, source[p]) - if ok && p == pos+1 { - data.MarkerAmbiguous = true - } - if ok { - data.MarkerFirstChar = b - } - return newPos, data, ok - } - } - - if isAlphaLower(b) { - if pos+1 < end && (source[pos+1] == '.' || source[pos+1] == ')') { - num := int(b - 'a' + 1) - newPos, data, ok := checkListItemEnd(source, startPos, pos+1, end, 'a', true, num, source[pos+1]) - if ok { - data.MarkerFirstChar = b - } - return newPos, data, ok - } - } - - if isRomanUpperStart(b) { - p := pos - for p < end && isRomanUpper(source[p]) { - p++ - } - if p < end && (source[p] == '.' || source[p] == ')') { - num := parseRoman(source[pos:p]) - newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'I', true, num, source[p]) - if ok && p == pos+1 { - data.MarkerAmbiguous = true - } - if ok { - data.MarkerFirstChar = b - } - return newPos, data, ok - } - } - - if isAlphaUpper(b) { - if pos+1 < end && (source[pos+1] == '.' || source[pos+1] == ')') { - num := int(b - 'A' + 1) - newPos, data, ok := checkListItemEnd(source, startPos, pos+1, end, 'A', true, num, source[pos+1]) - if ok { - data.MarkerFirstChar = b - } - return newPos, data, ok - } - } - - if b == '(' { - p := pos + 1 - if p < end { - b2 := source[p] - - if isDigit(b2) { - start := p - for p < end && isDigit(source[p]) { - p++ - } - if p < end && source[p] == ')' { - num := parseDecimal(source[start:p]) - newPos, data, ok := checkListItemEnd(source, startPos, p, end, '1', true, num, 'X') - if ok { - data.MarkerFirstChar = b2 - } - return newPos, data, ok - } - } - - if isAlphaLower(b2) && p+1 < end && source[p+1] == ')' { - num := int(b2 - 'a' + 1) - newPos, data, ok := checkListItemEnd(source, startPos, p+1, end, 'a', true, num, 'X') - if ok { - data.MarkerFirstChar = b2 - if isRomanLowerStart(b2) { - data.MarkerAmbiguous = true - } - } - return newPos, data, ok - } - if isAlphaUpper(b2) && p+1 < end && source[p+1] == ')' { - num := int(b2 - 'A' + 1) - newPos, data, ok := checkListItemEnd(source, startPos, p+1, end, 'A', true, num, 'X') - if ok { - data.MarkerFirstChar = b2 - if isRomanUpperStart(b2) { - data.MarkerAmbiguous = true - } - } - return newPos, data, ok - } - - if isRomanLowerStart(b2) { - start := p - for p < end && isRomanLower(source[p]) { - p++ - } - if p < end && source[p] == ')' { - if p > start+1 { - num := parseRoman(source[start:p]) - newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'i', true, num, 'X') - if ok { - data.MarkerFirstChar = b2 - } - return newPos, data, ok - } - } - } - - if isRomanUpperStart(b2) { - start := p - for p < end && isRomanUpper(source[p]) { - p++ - } - if p < end && source[p] == ')' { - if p > start+1 { - num := parseRoman(source[start:p]) - newPos, data, ok := checkListItemEnd(source, startPos, p, end, 'I', true, num, 'X') - if ok { - data.MarkerFirstChar = b2 - } - return newPos, data, ok - } - } - } - } - } - - return startPos, ContainerData{}, false -} - -func checkListItemEnd(source []byte, start, pos, end int32, style byte, ordered bool, num int, endChar byte) (int32, ContainerData, bool) { - if pos+1 == end || source[pos+1] == ' ' || source[pos+1] == '\t' { - newPos := pos + 1 - for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') { - newPos++ - } - indent := newPos - start - - checked := false - isTask := false - if !ordered && (style == '-' || style == '+' || style == '*') && newPos+3 <= end && source[newPos] == '[' { - if source[newPos+1] == ' ' && source[newPos+2] == ']' { - isTask = true - newPos += 3 - } else if (source[newPos+1] == 'x' || source[newPos+1] == 'X') && source[newPos+2] == ']' { - isTask = true - checked = true - newPos += 3 - } - - if isTask { - if newPos == end || source[newPos] == ' ' || source[newPos] == '\t' { - for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') { - newPos++ - } - indent = newPos - start - } else { - isTask = false - checked = false - newPos = pos + 1 - for newPos < end && (source[newPos] == ' ' || source[newPos] == '\t') { - newPos++ - } - indent = newPos - start - } - } - } - - if !ordered && indent == 1 && newPos < end { - return start, ContainerData{}, false - } - - return newPos, ContainerData{Marker: style, MarkerEnd: endChar, Ordered: ordered, IsTask: isTask, Checked: checked, Tight: true, NextNumber: num}, true - } - return start, ContainerData{}, false -} - -func parseDecimal(b []byte) int { - res := 0 - for _, c := range b { - res = res*10 + int(c-'0') - } - return res -} - -func parseRoman(b []byte) int { - val := func(c byte) int { - switch c { - case 'i', 'I': - return 1 - case 'v', 'V': - return 5 - case 'x', 'X': - return 10 - case 'l', 'L': - return 50 - case 'c', 'C': - return 100 - case 'd', 'D': - return 500 - case 'm', 'M': - return 1000 - } - return 0 - } - res := 0 - for i := 0; i < len(b); i++ { - v := val(b[i]) - if i+1 < len(b) && val(b[i+1]) > v { - res -= v - } else { - res += v - } - } - return res -} - -func isDigit(b byte) bool { - return b >= '0' && b <= '9' -} - -func isAlphaLower(b byte) bool { - return b >= 'a' && b <= 'z' -} - -func isAlphaUpper(b byte) bool { - return b >= 'A' && b <= 'Z' -} - -func isRomanLowerStart(b byte) bool { - switch b { - case 'i', 'v', 'x', 'l', 'c', 'd', 'm': - return true - } - return false -} - -func isRomanLower(b byte) bool { - return isRomanLowerStart(b) -} - -func isRomanUpperStart(b byte) bool { - switch b { - case 'I', 'V', 'X', 'L', 'C', 'D', 'M': - return true - } - return false -} - -func isRomanUpper(b byte) bool { - return isRomanUpperStart(b) -} diff --git a/scripts/mkman/djot/parser.go b/scripts/mkman/djot/parser.go @@ -1,17 +0,0 @@ -package djot - -func Parse(source []byte) *Document { - doc := &Document{Source: source} - bp := NewBlockParser(source) - - blockEvents := bp.Parse() - - ip := NewInlineParser(source) - inlineEvents := ip.Parse(blockEvents) - - as := Assembler{doc: doc} - as.Assemble(inlineEvents) - doc.Events = inlineEvents - - return doc -} diff --git a/scripts/mkman/main.go b/scripts/mkman/main.go @@ -8,12 +8,9 @@ import ( "path/filepath" "strings" "time" - - "aruu/mkman/djot" ) // Parse config.mk variables and values -// type Config map[string]string func parseConfigMk(path string) (Config, error) { @@ -75,7 +72,6 @@ func (cfg Config) isEnabled(key string) bool { } // Preprocessor condition stack for nested feature blocks -// type ifFrame struct { active bool seen bool @@ -121,7 +117,6 @@ func (s *ifStack) top() *ifFrame { } // Parse and evaluate preprocessor feature conditions -// func evalCondition(expr string, cfg Config) bool { expr = strings.TrimSpace(expr) if strings.HasPrefix(expr, "defined(") && strings.HasSuffix(expr, ")") { @@ -151,395 +146,7 @@ func evalCondition(expr string, cfg Config) bool { return cfg[expr] == "1" } -// Scanning and parsing djot comments in c source files -// -func formatToken(tok string) string { - if strings.HasPrefix(tok, "-") { - return "`" + tok + "`" - } - if len(tok) >= 2 { - first := tok[0] - last := tok[len(tok)-1] - if (first == '[' && last == ']') || (first == '<' && last == '>') || (first == '(' && last == ')') { - inner := tok[1 : len(tok)-1] - if strings.HasPrefix(inner, "-") { - return string(first) + "`" + inner + "`" + string(last) - } - return string(first) + "_" + inner + "_" + string(last) - } - } - return "_" + tok + "_" -} - -func parseNameSummary(line string) (string, string, bool) { - line = strings.TrimSpace(line) - if idx := strings.Index(line, ":"); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true - } - if idx := strings.Index(line, " \\- "); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+4:]), true - } - if idx := strings.Index(line, " - "); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+3:]), true - } - return "", "", false -} - -func isOptionPattern(s string) (string, string, bool) { - s = strings.TrimSpace(s) - if !strings.HasPrefix(s, "-") { - return "", "", false - } - idx := strings.Index(s, ":") - if idx < 0 { - return "", "", false - } - opt := strings.TrimSpace(s[:idx]) - desc := strings.TrimSpace(s[idx+1:]) - fields := strings.Fields(opt) - if len(fields) == 0 || !strings.HasPrefix(fields[0], "-") { - return "", "", false - } - return opt, desc, true -} - -func scanC(path string, cfg Config) (string, error) { - contentBytes, err := os.ReadFile(path) - if err != nil { - return "", err - } - contentStr := string(contentBytes) - - if !strings.Contains(contentStr, "?man") { - // Original parser mode using explicit man markers - var djotBuf strings.Builder - stack := &ifStack{} - sc := bufio.NewScanner(strings.NewReader(contentStr)) - sc.Buffer(make([]byte, 1<<20), 1<<20) - inBlockComment := false - - for sc.Scan() { - line := sc.Text() - trimmed := strings.TrimSpace(line) - - if inBlockComment { - if trimmed == "*/" || trimmed == "* /" { - inBlockComment = false - djotBuf.WriteByte('\n') - } else { - stripped := trimmed - if strings.HasPrefix(stripped, "* ") { - stripped = stripped[2:] - } else if stripped == "*" { - stripped = "" - } - djotBuf.WriteString(stripped) - djotBuf.WriteByte('\n') - } - continue - } - - if strings.HasPrefix(trimmed, "#") { - directive := trimmed[1:] - if ci := strings.Index(directive, "//"); ci >= 0 { - directive = directive[:ci] - } - directive = strings.TrimSpace(directive) - - switch { - case strings.HasPrefix(directive, "ifdef "): - key := strings.TrimSpace(directive[6:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && defined, defined) - case strings.HasPrefix(directive, "ifndef "): - key := strings.TrimSpace(directive[7:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && !defined, !defined) - case strings.HasPrefix(directive, "if "): - expr := strings.TrimSpace(directive[3:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - stack.push(pa && result, result) - case directive == "else": - if top := stack.top(); top != nil { - pa := stack.parentActive() - newActive := pa && !top.seen - top.active = newActive - top.seen = true - } - case strings.HasPrefix(directive, "elif "): - if top := stack.top(); top != nil { - expr := strings.TrimSpace(directive[5:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - newActive := pa && !top.seen && result - top.active = newActive - if result { - top.seen = true - } - } - case directive == "endif": - stack.pop() - } - continue - } - - if !stack.globallyActive() { - continue - } - - if strings.Contains(trimmed, "/* !man") { - startIdx := strings.Index(trimmed, "/* !man") - rest := strings.TrimSpace(trimmed[startIdx+7:]) - if strings.HasSuffix(rest, "*/") { - content := strings.TrimSpace(rest[:len(rest)-2]) - if content != "" { - djotBuf.WriteString(content) - djotBuf.WriteByte('\n') - } - } else { - if rest != "" { - djotBuf.WriteString(rest) - djotBuf.WriteByte('\n') - } - inBlockComment = true - } - continue - } - - if idx := strings.Index(trimmed, "// !man"); idx >= 0 { - content := strings.TrimSpace(trimmed[idx+7:]) - djotBuf.WriteString(content) - djotBuf.WriteByte('\n') - continue - } - } - - if err := sc.Err(); err != nil { - return "", err - } - return djotBuf.String(), nil - } - - // Heuristic parser mode using question mark man markers - type optionDoc struct { - opt string - desc string - } - type sectionDoc struct { - title string - lines []string - } - - var name, summary, synopsis string - var descriptionBody []string - var options []optionDoc - var otherSections []sectionDoc - var currentSection *sectionDoc - var lastOption *optionDoc - - stack := &ifStack{} - sc := bufio.NewScanner(strings.NewReader(contentStr)) - sc.Buffer(make([]byte, 1<<20), 1<<20) - inBlockComment := false - firstLineOfFirstBlock := true - - for sc.Scan() { - line := sc.Text() - trimmed := strings.TrimSpace(line) - - if inBlockComment { - if trimmed == "*/" || trimmed == "* /" { - inBlockComment = false - } else { - stripped := trimmed - if strings.HasPrefix(stripped, "* ") { - stripped = stripped[2:] - } else if stripped == "*" { - stripped = "" - } - if strings.HasPrefix(stripped, "// ?man ") { - stripped = stripped[8:] - } else if strings.HasPrefix(stripped, "// ?man") { - stripped = stripped[7:] - } - if firstLineOfFirstBlock { - firstLineOfFirstBlock = false - if n, s, ok := parseNameSummary(stripped); ok { - name = n - summary = s - continue - } - } - if synopsis == "" && strings.HasPrefix(strings.ToLower(stripped), "usage:") { - synopsis = strings.TrimSpace(stripped[6:]) - continue - } - if strings.HasPrefix(stripped, "## ") { - title := strings.TrimSpace(stripped[3:]) - otherSections = append(otherSections, sectionDoc{title: title}) - currentSection = &otherSections[len(otherSections)-1] - lastOption = nil - } else { - if opt, desc, ok := isOptionPattern(stripped); ok { - options = append(options, optionDoc{opt: opt, desc: desc}) - lastOption = &options[len(options)-1] - currentSection = nil - } else { - if currentSection != nil { - currentSection.lines = append(currentSection.lines, stripped) - } else { - descriptionBody = append(descriptionBody, stripped) - } - } - } - } - continue - } - - if strings.HasPrefix(trimmed, "#") { - directive := trimmed[1:] - if ci := strings.Index(directive, "//"); ci >= 0 { - directive = directive[:ci] - } - directive = strings.TrimSpace(directive) - - switch { - case strings.HasPrefix(directive, "ifdef "): - key := strings.TrimSpace(directive[6:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && defined, defined) - case strings.HasPrefix(directive, "ifndef "): - key := strings.TrimSpace(directive[7:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && !defined, !defined) - case strings.HasPrefix(directive, "if "): - expr := strings.TrimSpace(directive[3:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - stack.push(pa && result, result) - case directive == "else": - if top := stack.top(); top != nil { - pa := stack.parentActive() - newActive := pa && !top.seen - top.active = newActive - top.seen = true - } - case strings.HasPrefix(directive, "elif "): - if top := stack.top(); top != nil { - expr := strings.TrimSpace(directive[5:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - newActive := pa && !top.seen && result - top.active = newActive - if result { - top.seen = true - } - } - case directive == "endif": - stack.pop() - } - continue - } - - if !stack.globallyActive() { - continue - } - - if strings.Contains(trimmed, "/* ?man") { - startIdx := strings.Index(trimmed, "/* ?man") - rest := strings.TrimSpace(trimmed[startIdx+7:]) - if strings.HasSuffix(rest, "*/") { - content := strings.TrimSpace(rest[:len(rest)-2]) - if n, s, ok := parseNameSummary(content); ok { - name = n - summary = s - } - } else { - if rest != "" { - if n, s, ok := parseNameSummary(rest); ok { - name = n - summary = s - } else { - descriptionBody = append(descriptionBody, rest) - } - } - inBlockComment = true - } - continue - } - - if idx := strings.Index(trimmed, "// ?man"); idx >= 0 { - content := strings.TrimSpace(trimmed[idx+7:]) - if opt, desc, ok := isOptionPattern(content); ok { - options = append(options, optionDoc{opt: opt, desc: desc}) - lastOption = &options[len(options)-1] - currentSection = nil - } else { - if lastOption != nil { - lastOption.desc += " " + content - } else if currentSection != nil { - currentSection.lines = append(currentSection.lines, content) - } else { - descriptionBody = append(descriptionBody, content) - } - } - continue - } - } - - if err := sc.Err(); err != nil { - return "", err - } - - var djotBuf strings.Builder - djotBuf.WriteString("# " + name + "\n\n") - djotBuf.WriteString("## NAME\n\n") - djotBuf.WriteString(name + " \\- " + summary + "\n\n") - - if synopsis != "" { - djotBuf.WriteString("## SYNOPSIS\n\n") - djotBuf.WriteString("```\n" + synopsis + "\n```\n\n") - } - - if len(descriptionBody) > 0 { - djotBuf.WriteString("## DESCRIPTION\n\n") - for _, l := range descriptionBody { - djotBuf.WriteString(l + "\n") - } - djotBuf.WriteString("\n") - } - - if len(options) > 0 { - djotBuf.WriteString("## OPTIONS\n\n") - for _, opt := range options { - words := strings.Fields(opt.opt) - var formatted []string - for _, w := range words { - formatted = append(formatted, formatToken(w)) - } - djotBuf.WriteString(strings.Join(formatted, " ") + "\n") - djotBuf.WriteString(": " + opt.desc + "\n\n") - } - } - - for _, sec := range otherSections { - djotBuf.WriteString("## " + sec.title + "\n\n") - for _, l := range sec.lines { - djotBuf.WriteString(l + "\n") - } - djotBuf.WriteString("\n") - } - - return djotBuf.String(), nil -} - // Section inference from file path -// func inferSection(path string) int { clean := filepath.ToSlash(path) switch { @@ -553,7 +160,6 @@ func inferSection(path string) int { } // Main entry point and flags definition -// func main() { configPath := flag.String("config", "config.mk", "path to config.mk") sectionFlag := flag.Int("section", 0, "man section override (0 = infer from path)") @@ -579,22 +185,23 @@ func main() { date := *dateFlag if date == "" { - date = time.Now().Format("January 2006") + date = time.Now().Format("January 2, 2006") } - djotText, err := scanC(cfile, cfg) + page, err := ParsePage(cfile, cfg, section, date) if err != nil { fmt.Fprintf(os.Stderr, "mkman: scan: %v\n", err) os.Exit(1) } - if strings.TrimSpace(djotText) == "" { - fmt.Fprintf(os.Stderr, "mkman: %s: no !man comments found\n", cfile) + if page == nil { + fmt.Fprintf(os.Stderr, "mkman: %s: no ?man comments found\n", cfile) os.Exit(0) } - doc := djot.Parse([]byte(djotText)) - - r := NewTroffRenderer(doc, os.Stdout, section, date) - r.Render() + r := NewMdocRenderer(page, os.Stdout) + if err := r.Render(); err != nil { + fmt.Fprintf(os.Stderr, "mkman: render: %v\n", err) + os.Exit(1) + } } diff --git a/scripts/mkman/mdoc.go b/scripts/mkman/mdoc.go @@ -0,0 +1,251 @@ +package main + +import ( + "fmt" + "io" + "strings" +) + +type MdocRenderer struct { + page *Page + w io.Writer +} + +func NewMdocRenderer(page *Page, w io.Writer) *MdocRenderer { + return &MdocRenderer{page: page, w: w} +} + +func (r *MdocRenderer) Render() error { + if err := r.page.validate(); err != nil { + return err + } + + fmt.Fprintf(r.w, ".Dd %s\n", troffEscape(r.page.Date)) + fmt.Fprintf(r.w, ".Dt %s %d\n", strings.ToUpper(r.page.Name), r.page.Section) + fmt.Fprintf(r.w, ".Os %s\n", "aruu") + + r.renderName() + if len(r.page.Synopsis) != 0 { + r.renderSynopsis() + } + if len(r.page.Description) != 0 { + r.renderDescription() + } + if len(r.page.Options) != 0 { + r.renderOptions() + } + for _, section := range r.page.Sections { + r.renderSection(section.Title, section.Blocks) + } + return nil +} + +func (r *MdocRenderer) renderName() { + fmt.Fprintln(r.w, ".Sh NAME") + fmt.Fprintf(r.w, ".Nm %s\n", troffEscape(r.page.Name)) + fmt.Fprintf(r.w, ".Nd %s\n", renderInlineSeq(parseInlines(r.page.Summary))) +} + +func (r *MdocRenderer) renderDescription() { + fmt.Fprintln(r.w, ".Sh DESCRIPTION") + for _, block := range r.page.Description { + r.renderBlock(block) + } +} + +func (r *MdocRenderer) renderSynopsis() { + fmt.Fprintln(r.w, ".Sh SYNOPSIS") + for _, form := range r.page.Synopsis { + // synopsis macros are emitted one phrase per line + fmt.Fprintf(r.w, ".Nm %s\n", troffEscape(r.page.Name)) + for i := 0; i < len(form.Items); { + item := form.Items[i] + if item.Kind == SynOptional { + fmt.Fprintf(r.w, ".Op %s\n", renderSynopsisPhrase(item.Children, false)) + i++ + continue + } + + phrase, next := consumeSynopsisPhrase(form.Items, i) + fmt.Fprintln(r.w, renderSynopsisPhrase(phrase, true)) + i = next + } + } +} + +func consumeSynopsisPhrase(items []SynopsisItem, start int) ([]SynopsisItem, int) { + phrase := []SynopsisItem{items[start]} + i := start + 1 + + if items[start].Kind == SynFlag && i < len(items) && items[i].Kind == SynArg { + phrase = append(phrase, items[i]) + i++ + } + + for i+1 < len(items) && items[i].Kind == SynPipe { + phrase = append(phrase, items[i], items[i+1]) + i += 2 + } + + return phrase, i +} + +func renderSynopsisPhrase(items []SynopsisItem, topLevel bool) string { + var parts []string + for _, item := range items { + switch item.Kind { + case SynFlag: + parts = append(parts, renderMacro("Fl", troffEscape(strings.TrimPrefix(item.Text, "-")), topLevel && len(parts) == 0)) + case SynArg: + parts = append(parts, renderMacro("Ar", troffEscape(strings.Trim(item.Text, "<>")), topLevel && len(parts) == 0)) + case SynCommand: + parts = append(parts, renderMacro("Cm", troffEscape(item.Text), topLevel && len(parts) == 0)) + case SynPipe: + parts = append(parts, "|") + case SynLiteral: + parts = append(parts, troffEscape(item.Text)) + case SynOptional: + parts = append(parts, renderMacro("Op", renderSynopsisPhrase(item.Children, false), topLevel && len(parts) == 0)) + } + } + return strings.Join(parts, " ") +} + +func renderMacro(name, body string, topLevel bool) string { + if body == "" { + if topLevel { + return "." + name + } + return name + } + if topLevel { + return "." + name + " " + body + } + return name + " " + body +} + +func (r *MdocRenderer) renderOptions() { + fmt.Fprintln(r.w, ".Sh OPTIONS") + fmt.Fprintln(r.w, ".Bl -tag -width Ds") + for _, opt := range r.page.Options { + fmt.Fprintf(r.w, ".It %s\n", renderSynopsisPhrase(opt.Spec, false)) + for _, block := range opt.Body { + r.renderBlock(block) + } + } + fmt.Fprintln(r.w, ".El") +} + +func (r *MdocRenderer) renderSection(title string, blocks []Block) { + fmt.Fprintf(r.w, ".Sh %s\n", troffEscape(title)) + for _, block := range blocks { + r.renderBlock(block) + } +} + +func (r *MdocRenderer) renderBlock(block Block) { + switch block.Kind { + case BlockParagraph: + fmt.Fprintln(r.w, ".Pp") + fmt.Fprintf(r.w, ".No %s\n", renderInlineSeq(block.Inlines)) + case BlockTaggedList: + fmt.Fprintln(r.w, ".Bl -tag -width Ds") + for _, item := range block.Items { + fmt.Fprintf(r.w, ".It %s\n", renderInlineSeq(item.Label)) + if len(item.Body) != 0 { + fmt.Fprintln(r.w, ".Pp") + fmt.Fprintf(r.w, ".No %s\n", renderInlineSeq(item.Body)) + } + } + fmt.Fprintln(r.w, ".El") + case BlockSeeAlso: + for i, ref := range block.Refs { + line := fmt.Sprintf(".Xr %s %s", troffEscape(ref.Name), troffEscape(ref.Section)) + if i != len(block.Refs)-1 { + line += " ," + } + fmt.Fprintln(r.w, line) + } + case BlockSubsection: + fmt.Fprintf(r.w, ".Ss %s\n", troffEscape(block.Title)) + for _, child := range block.Blocks { + r.renderBlock(child) + } + } +} + +func troffEscape(s string) string { + s = strings.ReplaceAll(s, "\\", "\\\\") + s = strings.ReplaceAll(s, "-", "\\-") + if len(s) > 0 && s[0] == '.' { + s = "\\&" + s + } + return s +} + +func renderInlineSeq(inlines []Inline) string { + var b strings.Builder + // adjacent semantic nodes sometimes need to join without an intervening + // space, like some mixed path/emphasis/path forms in FILES + for i, inline := range inlines { + if i > 0 && needsNoSpace(inlines[i-1], inline) { + b.WriteString(" Ns ") + } + b.WriteString(renderInline(inline)) + } + return b.String() +} + +func renderInline(inline Inline) string { + switch inline.Kind { + case InlineText: + return troffEscape(inline.Text) + case InlineNm: + return renderMacro("Nm", "", false) + case InlineEmph: + return renderMacro("Em", renderInlineSeq(inline.Children), false) + case InlineLiteral: + return renderMacro("Ql", troffEscape(inline.Text), false) + case InlinePath: + return renderMacro("Pa", troffEscape(inline.Text), false) + case InlineXRef: + return renderMacro("Xr", troffEscape(inline.Text)+" "+troffEscape(inline.Section), false) + case InlineFlag: + return renderMacro("Fl", troffEscape(inline.Text), false) + default: + return "" + } +} + +func needsNoSpace(prev, curr Inline) bool { + if trailingSpace(prev) || leadingSpace(curr) { + return false + } + return true +} + +func leadingSpace(inline Inline) bool { + switch inline.Kind { + case InlineText: + return len(inline.Text) != 0 && isSpaceByte(inline.Text[0]) + case InlineEmph: + return len(inline.Children) != 0 && leadingSpace(inline.Children[0]) + default: + return false + } +} + +func trailingSpace(inline Inline) bool { + switch inline.Kind { + case InlineText: + return len(inline.Text) != 0 && isSpaceByte(inline.Text[len(inline.Text)-1]) + case InlineEmph: + return len(inline.Children) != 0 && trailingSpace(inline.Children[len(inline.Children)-1]) + default: + return false + } +} + +func isSpaceByte(b byte) bool { + return b == ' ' || b == '\t' || b == '\n' +} diff --git a/scripts/mkman/page.go b/scripts/mkman/page.go @@ -0,0 +1,92 @@ +package main + +type Page struct { + Name string + Summary string + Section int + Date string + Synopsis []SynopsisForm + Description []Block + Options []Option + Sections []Section +} + +type Section struct { + Title string + Blocks []Block +} + +type BlockKind int + +const ( + BlockParagraph BlockKind = iota + BlockTaggedList + BlockSeeAlso + BlockSubsection +) + +type Block struct { + Kind BlockKind + Inlines []Inline + Items []Item + Refs []XRef + Title string + Blocks []Block +} + +type Item struct { + Label []Inline + Body []Inline +} + +type XRef struct { + Name string + Section string +} + +type Option struct { + Spec []SynopsisItem + Desc string + Body []Block + Key string +} + +type SynopsisForm struct { + Items []SynopsisItem +} + +type SynopsisItemKind int + +const ( + SynFlag SynopsisItemKind = iota + SynArg + SynCommand + SynLiteral + SynOptional + SynPipe +) + +type SynopsisItem struct { + Kind SynopsisItemKind + Text string + Children []SynopsisItem +} + +type InlineKind int + +const ( + InlineText InlineKind = iota + InlineNm + InlineEmph + InlineLiteral + InlinePath + InlineXRef + InlineFlag +) + +type Inline struct { + Kind InlineKind + Text string + Section string + Children []Inline +} diff --git a/scripts/mkman/parse.go b/scripts/mkman/parse.go @@ -0,0 +1,951 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "regexp" + "slices" + "strings" +) + +var xrefPattern = regexp.MustCompile(`^\s*([A-Za-z0-9][A-Za-z0-9+_.-]*)\((\d+[A-Za-z]*)\)\s*$`) + +func parseNameSummary(line string) (string, string, bool) { + line = strings.TrimSpace(line) + if idx := strings.Index(line, ":"); idx >= 0 { + return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true + } + if idx := strings.Index(line, " \\- "); idx >= 0 { + return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+4:]), true + } + if idx := strings.Index(line, " - "); idx >= 0 { + return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+3:]), true + } + return "", "", false +} + +func extractManLines(path string, cfg Config) ([]string, error) { + contentBytes, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var lines []string + stack := &ifStack{} + sc := bufio.NewScanner(strings.NewReader(string(contentBytes))) + sc.Buffer(make([]byte, 1<<20), 1<<20) + inBlockComment := false + + for sc.Scan() { + line := sc.Text() + trimmed := strings.TrimSpace(line) + + if inBlockComment { + if trimmed == "*/" || trimmed == "* /" { + inBlockComment = false + continue + } + + stripped := trimmed + if strings.HasPrefix(stripped, "* ") { + stripped = stripped[2:] + } else if stripped == "*" { + stripped = "" + } + lines = append(lines, stripManPrefix(stripped)) + continue + } + + if strings.HasPrefix(trimmed, "#") { + directive := trimmed[1:] + if ci := strings.Index(directive, "//"); ci >= 0 { + directive = directive[:ci] + } + directive = strings.TrimSpace(directive) + + switch { + case strings.HasPrefix(directive, "ifdef "): + key := strings.TrimSpace(directive[6:]) + _, defined := cfg[key] + pa := stack.parentActive() + stack.push(pa && defined, defined) + case strings.HasPrefix(directive, "ifndef "): + key := strings.TrimSpace(directive[7:]) + _, defined := cfg[key] + pa := stack.parentActive() + stack.push(pa && !defined, !defined) + case strings.HasPrefix(directive, "if "): + expr := strings.TrimSpace(directive[3:]) + result := evalCondition(expr, cfg) + pa := stack.parentActive() + stack.push(pa && result, result) + case directive == "else": + if top := stack.top(); top != nil { + pa := stack.parentActive() + top.active = pa && !top.seen + top.seen = true + } + case strings.HasPrefix(directive, "elif "): + if top := stack.top(); top != nil { + expr := strings.TrimSpace(directive[5:]) + result := evalCondition(expr, cfg) + pa := stack.parentActive() + top.active = pa && !top.seen && result + if result { + top.seen = true + } + } + case directive == "endif": + stack.pop() + } + continue + } + + if !stack.globallyActive() { + continue + } + + if strings.Contains(trimmed, "/* ?man") { + startIdx := strings.Index(trimmed, "/* ?man") + rest := strings.TrimSpace(trimmed[startIdx+7:]) + if strings.HasSuffix(rest, "*/") { + lines = append(lines, strings.TrimSpace(rest[:len(rest)-2])) + } else { + lines = append(lines, rest) + inBlockComment = true + } + continue + } + + if idx := strings.Index(trimmed, "// ?man"); idx >= 0 { + lines = append(lines, strings.TrimSpace(trimmed[idx+7:])) + } + } + + if err := sc.Err(); err != nil { + return nil, err + } + return lines, nil +} + +func stripManPrefix(line string) string { + if strings.HasPrefix(line, "// ?man ") { + return line[8:] + } + if strings.HasPrefix(line, "// ?man") { + return line[7:] + } + return line +} + +func ParsePage(path string, cfg Config, section int, date string) (*Page, error) { + lines, err := extractManLines(path, cfg) + if err != nil { + return nil, err + } + + page := &Page{Section: section, Date: date} + + var descriptionLines []string + var sections []rawSection + var currentSection *rawSection + var sawContent bool + var fallbackArgs string + var rawOptions []rawOption + var currentOption *rawOption + optionIndex := make(map[string]int) + + for _, raw := range lines { + line := strings.TrimSpace(raw) + if line == "" { + if currentSection != nil { + currentSection.Lines = append(currentSection.Lines, "") + } else if currentOption != nil { + currentOption.Lines = append(currentOption.Lines, "") + } else if sawContent { + descriptionLines = append(descriptionLines, "") + } + continue + } + + if page.Name == "" && !strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "#") { + if name, summary, ok := parseNameSummary(line); ok { + page.Name = name + page.Summary = summary + sawContent = true + continue + } + } + + lower := strings.ToLower(line) + switch { + case strings.HasPrefix(lower, "synopsis:"): + currentOption = nil + form := strings.TrimSpace(line[len("synopsis:"):]) + if form != "" { + page.Synopsis = append(page.Synopsis, parseSynopsis(form, true)) + } + sawContent = true + continue + case strings.HasPrefix(lower, "arguments:"): + currentOption = nil + fallbackArgs = strings.TrimSpace(line[len("arguments:"):]) + sawContent = true + continue + case strings.HasPrefix(line, "## "): + currentOption = nil + title := strings.TrimSpace(line[3:]) + sections = append(sections, rawSection{Title: title}) + currentSection = &sections[len(sections)-1] + sawContent = true + continue + } + + if currentSection == nil { + if opt, ok := parseOption(line); ok { + rawOptions = append(rawOptions, rawOption{ + Option: opt, + Lines: []string{opt.Desc}, + }) + currentOption = &rawOptions[len(rawOptions)-1] + } else if isCodeLabel(line) || isCodeLabelPrefix(line) { + continue + } else if currentOption != nil { + currentOption.Lines = append(currentOption.Lines, line) + } else { + descriptionLines = append(descriptionLines, line) + } + sawContent = true + continue + } + + currentSection.Lines = append(currentSection.Lines, line) + sawContent = true + } + + if !sawContent || page.Name == "" { + return nil, nil + } + + // explicit 'synopsis' forms are authoritative. for simple pages we can produce + // a synopsis from the parsed option specs plus the 'arguments' + for _, raw := range rawOptions { + raw.Option.Body = parseBlocks(raw.Lines, "") + addOption(page, optionIndex, raw.Option) + } + + if len(page.Synopsis) == 0 && fallbackArgs != "" { + page.Synopsis = append(page.Synopsis, synthesizeSynopsis(page.Options, fallbackArgs)) + } + + page.Description = parseBlocks(descriptionLines, "") + for _, section := range sections { + page.Sections = append(page.Sections, Section{ + Title: section.Title, + Blocks: parseBlocks(section.Lines, section.Title), + }) + } + normalizePageInlines(page) + + return page, nil +} + +type rawSection struct { + Title string + Lines []string +} + +type rawOption struct { + Option Option + Lines []string +} + +func parseOption(line string) (Option, bool) { + if !strings.HasPrefix(line, "-") { + return Option{}, false + } + + parts := strings.Split(line, ":") + if len(parts) < 2 { + return Option{}, false + } + + specParts := []string{strings.TrimSpace(parts[0])} + i := 1 + for i < len(parts)-1 { + part := strings.TrimSpace(parts[i]) + if !looksLikeOptionArg(part) { + break + } + specParts = append(specParts, part) + i++ + } + + desc := strings.TrimSpace(strings.Join(parts[i:], ":")) + spec := normalizeOptionSpec(strings.Join(specParts, ":")) + desc = stripRepeatedSpec(spec, desc) + if spec == "" || desc == "" { + return Option{}, false + } + + return Option{ + Spec: parseSynopsis(spec, false).Items, + Desc: desc, + Key: synopsisKey(spec), + }, true +} + +func looksLikeOptionArg(s string) bool { + if s == "" { + return false + } + return !strings.ContainsAny(s, " \t") +} + +func normalizeOptionSpec(spec string) string { + spec = strings.TrimSpace(spec) + if spec == "" { + return "" + } + + parts := strings.Split(spec, ":") + if len(parts) == 1 { + return strings.Join(strings.Fields(spec), " ") + } + + normalized := []string{strings.TrimSpace(parts[0])} + for _, part := range parts[1:] { + part = strings.TrimSpace(part) + if part == "" { + continue + } + normalized = append(normalized, part) + } + return strings.Join(normalized, " ") +} + +func stripRepeatedSpec(spec, desc string) string { + spec = strings.TrimSpace(spec) + desc = strings.TrimSpace(desc) + candidates := []string{ + spec + ":", + strings.ReplaceAll(spec, " ", ":") + ":", + } + for _, candidate := range candidates { + if strings.HasPrefix(desc, candidate) { + return strings.TrimSpace(desc[len(candidate):]) + } + } + return desc +} + +func addOption(page *Page, index map[string]int, opt Option) { + if idx, ok := index[opt.Key]; ok { + if betterOptionDesc(opt.Desc, page.Options[idx].Desc) { + page.Options[idx].Desc = opt.Desc + page.Options[idx].Spec = opt.Spec + page.Options[idx].Body = opt.Body + } + return + } + + primary := optionPrimaryFlag(opt) + if primary != "" { + for idx, existing := range page.Options { + if optionPrimaryFlag(existing) != primary { + continue + } + if betterOptionDesc(opt.Desc, existing.Desc) { + page.Options[idx].Desc = opt.Desc + page.Options[idx].Spec = opt.Spec + page.Options[idx].Body = opt.Body + delete(index, existing.Key) + index[opt.Key] = idx + } + return + } + } + + index[opt.Key] = len(page.Options) + page.Options = append(page.Options, opt) +} + +func betterOptionDesc(newDesc, oldDesc string) bool { + return optionDescScore(newDesc) > optionDescScore(oldDesc) +} + +func optionDescScore(desc string) int { + desc = strings.TrimSpace(desc) + score := len(desc) + lower := strings.ToLower(desc) + if strings.HasPrefix(lower, "specify ") && strings.HasSuffix(lower, " option") { + score -= 1000 + } + return score +} + +func optionPrimaryFlag(opt Option) string { + for _, item := range opt.Spec { + if item.Kind == SynFlag { + return item.Text + } + } + return "" +} + +func synopsisKey(spec string) string { + return strings.Join(strings.Fields(spec), " ") +} + +func isCodeLabel(line string) bool { + if !strings.HasSuffix(line, ":") { + return false + } + for _, r := range line[:len(line)-1] { + if (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' { + return false + } + } + return len(line) > 1 +} + +func isCodeLabelPrefix(line string) bool { + idx := strings.IndexByte(line, ':') + if idx <= 0 { + return false + } + return isCodeLabel(line[:idx+1]) +} + +func parseBlocks(lines []string, title string) []Block { + lines = trimBlankLines(lines) + if len(lines) == 0 { + return nil + } + + if blocks, ok := parseSubsections(lines, title); ok { + return blocks + } + + if items, ok := parseHeadingItems(lines); ok { + return []Block{{Kind: BlockTaggedList, Items: items}} + } + + if items, ok := parseSequentialTaggedItems(lines); ok { + return []Block{{Kind: BlockTaggedList, Items: items}} + } + + paragraphs := splitParagraphs(lines) + var blocks []Block + + for _, paragraph := range paragraphs { + if len(paragraph) == 0 { + continue + } + + if isSeeAlsoTitle(title) { + if refs, ok := parseXRefs(strings.Join(paragraph, " ")); ok { + slices.SortFunc(refs, func(a, b XRef) int { + if a.Section != b.Section { + return strings.Compare(a.Section, b.Section) + } + return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name)) + }) + blocks = append(blocks, Block{Kind: BlockSeeAlso, Refs: refs}) + continue + } + } + + if item, ok := parseTaggedItem(paragraph); ok { + if len(blocks) != 0 && blocks[len(blocks)-1].Kind == BlockTaggedList { + blocks[len(blocks)-1].Items = append(blocks[len(blocks)-1].Items, item) + } else { + blocks = append(blocks, Block{Kind: BlockTaggedList, Items: []Item{item}}) + } + continue + } + + blocks = append(blocks, Block{ + Kind: BlockParagraph, + Inlines: parseInlines(strings.Join(paragraph, " ")), + }) + } + + return blocks +} + +func parseSubsections(lines []string, title string) ([]Block, bool) { + hasHeading := false + for _, line := range lines { + if strings.HasPrefix(strings.TrimSpace(line), "### ") { + hasHeading = true + break + } + } + if !hasHeading { + return nil, false + } + + var blocks []Block + var preamble []string + for len(lines) != 0 && !strings.HasPrefix(strings.TrimSpace(lines[0]), "### ") { + preamble = append(preamble, lines[0]) + lines = lines[1:] + } + if parsed := parseBlocks(preamble, title); len(parsed) != 0 { + blocks = append(blocks, parsed...) + } + + for len(lines) != 0 { + head := strings.TrimSpace(lines[0]) + if !strings.HasPrefix(head, "### ") { + return nil, false + } + subtitle := strings.TrimSpace(head[4:]) + lines = lines[1:] + var body []string + for len(lines) != 0 && !strings.HasPrefix(strings.TrimSpace(lines[0]), "### ") { + body = append(body, lines[0]) + lines = lines[1:] + } + blocks = append(blocks, Block{ + Kind: BlockSubsection, + Title: subtitle, + Blocks: parseBlocks(body, subtitle), + }) + } + + return blocks, true +} + +func trimBlankLines(lines []string) []string { + start := 0 + for start < len(lines) && strings.TrimSpace(lines[start]) == "" { + start++ + } + end := len(lines) + for end > start && strings.TrimSpace(lines[end-1]) == "" { + end-- + } + return lines[start:end] +} + +func splitParagraphs(lines []string) [][]string { + var paragraphs [][]string + var current []string + for _, line := range lines { + if strings.TrimSpace(line) == "" { + if len(current) != 0 { + paragraphs = append(paragraphs, current) + current = nil + } + continue + } + current = append(current, line) + } + if len(current) != 0 { + paragraphs = append(paragraphs, current) + } + return paragraphs +} + +func parseHeadingItems(lines []string) ([]Item, bool) { + var items []Item + var current *Item + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + if strings.HasPrefix(line, "### ") { + items = append(items, Item{Label: parseInlines(strings.TrimSpace(line[4:]))}) + current = &items[len(items)-1] + continue + } + if current == nil { + return nil, false + } + if len(current.Body) != 0 { + current.Body = append(current.Body, Inline{Kind: InlineText, Text: " "}) + } + current.Body = append(current.Body, parseInlines(strings.TrimSpace(line))...) + } + return items, len(items) != 0 +} + +func parseSequentialTaggedItems(lines []string) ([]Item, bool) { + var items []Item + for i := 0; i < len(lines); { + for i < len(lines) && strings.TrimSpace(lines[i]) == "" { + i++ + } + if i >= len(lines) { + break + } + + label := strings.TrimSpace(lines[i]) + if label == "" || i+1 >= len(lines) { + return nil, false + } + first := strings.TrimSpace(lines[i+1]) + if !strings.HasPrefix(first, ":") { + return nil, false + } + + bodyLines := []string{strings.TrimSpace(strings.TrimPrefix(first, ":"))} + i += 2 + for i < len(lines) { + line := strings.TrimSpace(lines[i]) + if line == "" { + i++ + break + } + if i+1 < len(lines) && strings.TrimSpace(lines[i]) != "" && + strings.HasPrefix(strings.TrimSpace(lines[i+1]), ":") { + break + } + bodyLines = append(bodyLines, line) + i++ + } + + items = append(items, Item{ + Label: parseInlines(label), + Body: parseInlines(strings.Join(compactLines(bodyLines), " ")), + }) + } + return items, len(items) != 0 +} + +func parseTaggedItem(lines []string) (Item, bool) { + if len(lines) < 2 { + return Item{}, false + } + label := strings.TrimSpace(lines[0]) + bodyLines := lines[1:] + if label == "" { + return Item{}, false + } + + first := strings.TrimSpace(bodyLines[0]) + if !strings.HasPrefix(first, ":") { + return Item{}, false + } + + bodyLines[0] = strings.TrimSpace(strings.TrimPrefix(first, ":")) + return Item{ + Label: parseInlines(label), + Body: parseInlines(strings.Join(compactLines(bodyLines), " ")), + }, true +} + +func parseInlines(s string) []Inline { + var out []Inline + var text strings.Builder + flushText := func() { + if text.Len() == 0 { + return + } + out = append(out, Inline{Kind: InlineText, Text: text.String()}) + text.Reset() + } + + // inline semantics are parsed here so the renderer never has to recover + // any richness like paths, flags, emphasis, or xrefs by reparsing raw strings + for i := 0; i < len(s); { + switch s[i] { + case '`': + end := strings.IndexByte(s[i+1:], '`') + if end < 0 { + text.WriteByte(s[i]) + i++ + continue + } + end += i + 1 + flushText() + out = append(out, classifyInlineLiteral(s[i+1:end])) + i = end + 1 + case '_': + end := strings.IndexByte(s[i+1:], '_') + if end < 0 { + text.WriteByte(s[i]) + i++ + continue + } + end += i + 1 + flushText() + out = append(out, Inline{ + Kind: InlineEmph, + Children: parseInlines(s[i+1 : end]), + }) + i = end + 1 + default: + text.WriteByte(s[i]) + i++ + } + } + + flushText() + return out +} + +func classifyInlineLiteral(s string) Inline { + s = strings.TrimSpace(s) + if match := xrefPattern.FindStringSubmatch(s); match != nil { + return Inline{Kind: InlineXRef, Text: match[1], Section: match[2]} + } + if strings.HasPrefix(s, "/") { + return Inline{Kind: InlinePath, Text: s} + } + if strings.HasPrefix(s, "-") { + return Inline{Kind: InlineFlag, Text: strings.TrimPrefix(s, "-")} + } + return Inline{Kind: InlineLiteral, Text: s} +} + +func synthesizeSynopsis(options []Option, args string) SynopsisForm { + var items []SynopsisItem + for _, opt := range sortedOptions(options) { + items = append(items, SynopsisItem{ + Kind: SynOptional, + Children: cloneSynopsisItems(opt.Spec), + }) + } + items = append(items, parseSynopsis(args, false).Items...) + return SynopsisForm{Items: items} +} + +func sortedOptions(options []Option) []Option { + out := append([]Option(nil), options...) + slices.SortFunc(out, func(a, b Option) int { + return strings.Compare(optionSortKey(a), optionSortKey(b)) + }) + return out +} + +func optionSortKey(opt Option) string { + flag := optionPrimaryFlag(opt) + if flag == "" { + return "zzzz" + } + r := flag[0] + prefix := "2" + switch { + case r >= '0' && r <= '9': + prefix = "0" + case r >= 'A' && r <= 'Z': + prefix = "1" + } + return prefix + flag +} + +func cloneSynopsisItems(items []SynopsisItem) []SynopsisItem { + out := make([]SynopsisItem, len(items)) + for i, item := range items { + out[i] = item + if len(item.Children) != 0 { + out[i].Children = cloneSynopsisItems(item.Children) + } + } + return out +} + +func compactLines(lines []string) []string { + var out []string + for _, line := range lines { + line = strings.TrimSpace(line) + if line != "" { + out = append(out, line) + } + } + return out +} + +func isSeeAlsoTitle(title string) bool { + return strings.EqualFold(strings.TrimSpace(title), "SEE ALSO") +} + +func parseXRefs(s string) ([]XRef, bool) { + var refs []XRef + for _, part := range strings.Split(s, ",") { + part = strings.TrimSpace(part) + match := xrefPattern.FindStringSubmatch(part) + if match == nil { + return nil, false + } + refs = append(refs, XRef{Name: match[1], Section: match[2]}) + } + return refs, len(refs) != 0 +} + +func parseSynopsis(raw string, explicit bool) SynopsisForm { + tokens := tokenizeSynopsis(raw) + items, _ := parseSynopsisSeq(tokens, 0, explicit, true) + return SynopsisForm{Items: items} +} + +func tokenizeSynopsis(raw string) []string { + var tokens []string + var current strings.Builder + flush := func() { + if current.Len() != 0 { + tokens = append(tokens, current.String()) + current.Reset() + } + } + + for i := 0; i < len(raw); i++ { + ch := raw[i] + switch ch { + case '[', ']', '|': + flush() + tokens = append(tokens, string(ch)) + case ' ', '\t', '\n': + flush() + default: + current.WriteByte(ch) + } + } + flush() + return tokens +} + +func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) ([]SynopsisItem, int) { + var items []SynopsisItem + seenNonFlag := false + + for i := start; i < len(tokens); i++ { + switch tokens[i] { + case "]": + return items, i + case "[": + children, end := parseSynopsisSeq(tokens, i+1, explicit, false) + items = append(items, SynopsisItem{Kind: SynOptional, Children: children}) + i = end + case "|": + items = append(items, SynopsisItem{Kind: SynPipe, Text: "|"}) + default: + if flags, ok := splitGroupedFlags(tokens[i]); ok { + items = append(items, flags...) + continue + } + kind := classifySynopsisToken(tokens, i, explicit, topLevel, seenNonFlag) + text := tokens[i] + if text == "..." && len(items) != 0 { + items[len(items)-1].Text += " ..." + continue + } + items = append(items, SynopsisItem{Kind: kind, Text: text}) + if kind != SynFlag && kind != SynPipe { + seenNonFlag = true + } + } + } + + return items, len(tokens) +} + +func splitGroupedFlags(tok string) ([]SynopsisItem, bool) { + // We expand compacted synopsis tokens like some -abcDef into separate + // semantic flags so the renderer can emit a separate Fl for each one. + if len(tok) < 3 || tok[0] != '-' { + return nil, false + } + for i := 1; i < len(tok); i++ { + c := tok[i] + if (c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') { + return nil, false + } + } + + items := make([]SynopsisItem, 0, len(tok)-1) + for i := 1; i < len(tok); i++ { + items = append(items, SynopsisItem{ + Kind: SynFlag, + Text: "-" + string(tok[i]), + }) + } + return items, true +} + +func classifySynopsisToken(tokens []string, i int, explicit, topLevel, seenNonFlag bool) SynopsisItemKind { + tok := tokens[i] + if strings.HasPrefix(tok, "-") { + return SynFlag + } + if strings.HasPrefix(tok, "<") && strings.HasSuffix(tok, ">") { + return SynArg + } + if strings.Contains(tok, "...") || strings.ContainsAny(tok, "/=:") { + return SynArg + } + if i > 0 && tokens[i-1] == "|" { + if explicit { + return SynCommand + } + return SynArg + } + if i+1 < len(tokens) && tokens[i+1] == "|" { + if explicit { + return SynCommand + } + return SynArg + } + if i > 0 && strings.HasPrefix(tokens[i-1], "-") { + return SynArg + } + if explicit && topLevel && !seenNonFlag && i+1 < len(tokens) && tokens[i+1] == "[" { + return SynCommand + } + return SynArg +} + +func (p *Page) validate() error { + if p.Name == "" { + return fmt.Errorf("missing manpage name") + } + if p.Summary == "" { + return fmt.Errorf("missing manpage summary") + } + return nil +} + +func normalizePageInlines(page *Page) { + for i := range page.Description { + page.Description[i] = mergeAdjacentTextInBlock(page.Description[i]) + } + for i := range page.Options { + for j := range page.Options[i].Body { + page.Options[i].Body[j] = mergeAdjacentTextInBlock(page.Options[i].Body[j]) + } + } + for i := range page.Sections { + for j := range page.Sections[i].Blocks { + page.Sections[i].Blocks[j] = mergeAdjacentTextInBlock(page.Sections[i].Blocks[j]) + } + } +} + +func mergeAdjacentTextInBlock(block Block) Block { + block.Inlines = mergeAdjacentText(block.Inlines) + for i := range block.Items { + block.Items[i].Label = mergeAdjacentText(block.Items[i].Label) + block.Items[i].Body = mergeAdjacentText(block.Items[i].Body) + } + return block +} + +func mergeAdjacentText(inlines []Inline) []Inline { + if len(inlines) == 0 { + return nil + } + out := []Inline{inlines[0]} + for _, inline := range inlines[1:] { + last := &out[len(out)-1] + if last.Kind == InlineText && inline.Kind == InlineText { + last.Text += inline.Text + continue + } + out = append(out, inline) + } + return out +} diff --git a/scripts/mkman/troff.go b/scripts/mkman/troff.go @@ -1,248 +0,0 @@ -package main - -import ( - "fmt" - "io" - "strings" - - "aruu/mkman/djot" -) - -type TroffRenderer struct { - doc *djot.Document - w io.Writer - section int - date string - thDone bool - listDepth int -} - -func NewTroffRenderer(doc *djot.Document, w io.Writer, section int, date string) *TroffRenderer { - return &TroffRenderer{doc: doc, w: w, section: section, date: date} -} - -func (r *TroffRenderer) getBytes(start, end int32) []byte { - if start == -1 && end == -1 { - return nil - } - if start < 0 { - idx := ^start - if idx < 0 || idx >= int32(len(r.doc.Extra)) { - return nil - } - return r.doc.Extra[idx : end+1] - } - if start >= int32(len(r.doc.Source)) || end >= int32(len(r.doc.Source)) || start > end { - return nil - } - return r.doc.Source[start : end+1] -} - -func troffEscape(s string) string { - s = strings.ReplaceAll(s, "\\", "\\\\") - s = strings.ReplaceAll(s, "-", "\\-") - // Leading dot is escaped to prevent troff from treating it as a macro - if len(s) > 0 && s[0] == '.' { - s = "\\&" + s - } - return s -} - -func (r *TroffRenderer) collectInlineText(idx int32) string { - var b strings.Builder - curr := r.doc.Nodes[idx].Child - for curr != -1 { - node := r.doc.Nodes[curr] - switch node.Type { - case djot.NodeStr: - b.Write(r.getBytes(node.Start, node.End)) - case djot.NodeSoftBreak: - b.WriteRune(' ') - case djot.NodeVerbatim: - b.Write(r.getBytes(node.Start, node.End)) - default: - b.WriteString(r.collectInlineText(curr)) - } - curr = node.Next - } - return b.String() -} - -func (r *TroffRenderer) renderInlines(idx int32) { - curr := r.doc.Nodes[idx].Child - for curr != -1 { - r.renderInlineNode(curr) - curr = r.doc.Nodes[curr].Next - } -} - -func (r *TroffRenderer) renderInlineNode(idx int32) { - node := r.doc.Nodes[idx] - switch node.Type { - case djot.NodeStr: - raw := string(r.getBytes(node.Start, node.End)) - fmt.Fprint(r.w, troffEscape(raw)) - case djot.NodeSoftBreak: - fmt.Fprint(r.w, " ") - case djot.NodeHardBreak: - fmt.Fprint(r.w, "\n.br\n") - case djot.NodeNonBreakingSpace: - fmt.Fprint(r.w, "\\ ") - case djot.NodeEmph: - fmt.Fprint(r.w, `\fI`) - r.renderInlines(idx) - fmt.Fprint(r.w, `\fP`) - case djot.NodeStrong: - fmt.Fprint(r.w, `\fB`) - r.renderInlines(idx) - fmt.Fprint(r.w, `\fP`) - case djot.NodeVerbatim: - fmt.Fprint(r.w, `\fB`) - raw := string(r.getBytes(node.Start, node.End)) - fmt.Fprint(r.w, troffEscape(raw)) - fmt.Fprint(r.w, `\fP`) - case djot.NodeSmartPunctuation: - data := node.Data - switch data { - case 1: - fmt.Fprint(r.w, `\(em`) - case 2: - fmt.Fprint(r.w, `\(en`) - default: - fmt.Fprint(r.w, `\-\-`) - } - case djot.NodeLink: - // Render link text only because raw urls are typically omitted in man pages - r.renderInlines(idx) - case djot.NodeDoubleQuoted: - fmt.Fprint(r.w, `\(lq`) - r.renderInlines(idx) - fmt.Fprint(r.w, `\(rq`) - case djot.NodeSingleQuoted: - fmt.Fprint(r.w, `\(oq`) - r.renderInlines(idx) - fmt.Fprint(r.w, `\(cq`) - default: - r.renderInlines(idx) - } -} - -func (r *TroffRenderer) renderChildren(idx int32) { - curr := r.doc.Nodes[idx].Child - for curr != -1 { - r.renderNode(curr) - curr = r.doc.Nodes[curr].Next - } -} - -func (r *TroffRenderer) renderNode(idx int32) { - node := r.doc.Nodes[idx] - switch node.Type { - case djot.NodeDoc: - r.renderChildren(idx) - - case djot.NodeSection: - r.renderChildren(idx) - - case djot.NodeHeading: - level := int(node.Level) - if level == 0 { - level = int(node.Data & 0xFFFF) - } - text := r.collectInlineText(idx) - switch level { - case 1: - if !r.thDone { - fmt.Fprintf(r.w, ".TH %s %d \"%s\"\n", - strings.ToUpper(text), r.section, r.date) - r.thDone = true - } else { - fmt.Fprintf(r.w, ".SH %s\n", strings.ToUpper(text)) - } - case 2: - fmt.Fprintf(r.w, ".SH %s\n", strings.ToUpper(text)) - case 3: - fmt.Fprintf(r.w, ".SS %s\n", text) - default: - fmt.Fprintf(r.w, ".PP\n\\fB%s\\fP\n", troffEscape(text)) - } - - case djot.NodePara: - if r.listDepth > 0 { - r.renderInlines(idx) - fmt.Fprint(r.w, "\n") - } else { - fmt.Fprint(r.w, ".PP\n") - r.renderInlines(idx) - fmt.Fprint(r.w, "\n") - } - - case djot.NodeCodeBlock: - fmt.Fprint(r.w, ".nf\n") - if node.Child != -1 { - r.renderChildren(idx) - } else { - raw := r.getBytes(node.Start, node.End) - r.w.Write(raw) //nolint - } - fmt.Fprint(r.w, ".fi\n") - - case djot.NodeStr: - raw := string(r.getBytes(node.Start, node.End)) - fmt.Fprint(r.w, raw) - - case djot.NodeBlockQuote: - fmt.Fprint(r.w, ".RS\n") - r.renderChildren(idx) - fmt.Fprint(r.w, ".RE\n") - - case djot.NodeBulletList, djot.NodeOrderedList, djot.NodeTaskList: - r.listDepth++ - r.renderChildren(idx) - r.listDepth-- - - case djot.NodeListItem, djot.NodeTaskListItem: - if r.doc.Nodes[idx].Type == djot.NodeTaskListItem { - checked := (node.Data & djot.DataTaskChecked) != 0 - if checked { - fmt.Fprint(r.w, ".IP \"[x]\" 4\n") - } else { - fmt.Fprint(r.w, ".IP \"[ ]\" 4\n") - } - } else { - fmt.Fprint(r.w, ".IP \\(bu 4\n") - } - r.renderChildren(idx) - - case djot.NodeDefinitionList: - r.renderChildren(idx) - - case djot.NodeDefinitionListItem: - r.renderChildren(idx) - - case djot.NodeTerm: - fmt.Fprint(r.w, ".TP\n") - r.renderInlines(idx) - fmt.Fprint(r.w, "\n") - - case djot.NodeDefinition: - r.listDepth++ - r.renderChildren(idx) - r.listDepth-- - - case djot.NodeThematicBreak: - // Omit thematic breaks because troff lacks a clean representation - - case djot.NodeDiv: - r.renderChildren(idx) - - default: - } -} - -func (r *TroffRenderer) Render() { - if len(r.doc.Nodes) == 0 { - return - } - r.renderNode(0) -}