// ZSH-SUDO — ENGINEERING REPORT

zsh plugin · ZLE widget · toggles sudo on the current command line · LBUFFER then RBUFFER strip · fc -ln -1 empty-BUFFER recall · configurable command + regex

>_EXECUTIVE SUMMARY

zsh-sudo registers one ZLE widget — sudo-command-line — that toggles sudo on the current command line. The widget runs in three modes: (1) BUFFER empty → pull the previous command via builtin fc -ln -1 and prepend; (2) BUFFER already starts with sudo (after any leading whitespace, var-assignments, builtin/command/env wrappers, and stacked sudo flags) → strip the whole prefix; (3) otherwise → prepend $ZPWR_SUDO_CMD. The matching is two parallel regex patterns: one against $LBUFFER (cursor at or after sudo), one against $RBUFFER (cursor before sudo) — so the toggle works regardless of where the user's cursor sits on a long line. Both the command word and the regex are environment-configurable so the same widget works for doas, please, run0, or any other privilege-escalation tool.

38
Plugin LOC
1
ZLE Widget
2
Env Vars
2
Match Sides (L/R)
101
zunit @test Cases
6
Test Files
21
Docs/Repo Gates
34
Git Commits

Test Density — 101 cases against 38 LOC

2.66 zunit @test cases per LOC of widget body

The widget is small but every code path is a regex branch that must hold across edge cases — quoted commands, env-prefixed runs, stacked sudo flags, var-assignments before sudo, custom command names, RBUFFER-side matches. Test density tracks the regex's branching: t-sudo-command-line.zsh alone carries 81 cases.


#FILE STRUCTURE

FileLinesRole
sudo.plugin.zsh38Entrypoint + widget body. ZPWR_SUDO_CMD + ZPWR_SUDO_REGEX defaults, sudo-command-line fn (empty-BUFFER recall + LBUFFER regex strip + RBUFFER regex strip + prepend fallthrough), zle -N sudo-command-line
1 source file38Single-file plugin

No autoload/, no src/, no completions/ directory. The whole plugin is one file. The keybinding itself is intentionally not set by the plugin — the README documents the canonical pattern (bindkey '^N' sudo-command-line) but leaves the user to choose their chord. The widely-published "Esc Esc" binding in oh-my-zsh's stock sudo plugin is one of many valid choices; this plugin doesn't force one.


$ENV CONTRACT

Two env vars, both only set when unset. The user controls the strip-and-prepend tool by exporting these before sourcing the plugin.

Env varDefaultRole
ZPWR_SUDO_CMDsudoString prepended to the buffer when there's nothing to strip. Set to doas, please, etc. to use a different privilege-escalation tool.
ZPWR_SUDO_REGEXsudoRegex fragment the strip-side hunts for. Should match ZPWR_SUDO_CMD in practice. Decoupled from the prepend string so the regex can support alternation (e.g. (sudo|doas)) without forcing the prepend to pick one.

Both vars are guarded by (( $+ZPWR_SUDO_CMD )) / (( $+ZPWR_SUDO_REGEX )), so re-sourcing the plugin won't clobber a user override and the unset path is the only path that writes a default.


@WIDGET FLOW

Single fn, three branches. Order is fixed: empty-BUFFER recall first, then LBUFFER strip attempt, then RBUFFER strip attempt, then unconditional prepend. The LBUFFER/RBUFFER split is the load-bearing trick — it preserves cursor position on long lines.

  ^X invoked (any keybinding chosen by user)
       │
       ▼
  ┌──────────────────────────────────────┐
  │ BUFFER empty?                        │
  │   yes → LBUFFER = "$(fc -ln -1)"     │ ← pull last cmd from history
  │   no  → leave BUFFER as-is           │
  └────────────────┬─────────────────────┘
                   │
                   ▼
  ┌──────────────────────────────────────┐
  │ LBUFFER matches sudo-prefix regex?   │
  │   yes → LBUFFER = "$match[1]$match[-1]"  │ ← strip whole prefix
  │   no  → fallthrough                  │     keep leading whitespace
  └────────────────┬─────────────────────┘     + post-sudo command
                   │
                   ▼ (no LBUFFER match)
  ┌──────────────────────────────────────┐
  │ RBUFFER matches sudo-prefix regex?   │
  │   yes → RBUFFER = "$match[1]$match[-1]"  │
  │   no  → fallthrough                  │
  └────────────────┬─────────────────────┘
                   │
                   ▼ (neither side matched)
  ┌──────────────────────────────────────┐
  │ LBUFFER = "$ZPWR_SUDO_CMD $LBUFFER"  │ ← unconditional prepend
  └──────────────────────────────────────┘

The cursor doesn't move on toggle — $LBUFFER and $RBUFFER are zsh's split of the command line at the cursor position, so editing the side the cursor isn't on preserves the cursor's column. This is what makes the widget feel like a true toggle: hit the chord twice and you're back where you started, character-for-character.


&REGEX ANATOMY

One regex pattern, applied twice (LBUFFER + RBUFFER). It's a 700-character beast covering 8 grammar classes of "this counts as a sudo invocation." Each class below is a section of the pattern; the strip path drops everything matched and leaves $match[1] (leading whitespace) + $match[-1] (the trailing command and its args).

Pattern fragmentCatches
^([[:space:]]*)Leading whitespace (preserved as $match[1])
([[:graph:]]+=[[:graph:]]+[[:space:]]+)*Var assignments before sudo: FOO=bar BAR=baz sudo cmd
(([\\\"\']*builtin[\\\"\']*[[:space:]]+)*[\\\"\']*command[\\\"\']*)?Optional builtin + command wrapper words, possibly quoted
[\\\"\']*"$ZPWR_SUDO_REGEX"[\\\"\']*The sudo command name itself, optionally quoted; pluggable via env var
(-[ABbEHnPSis]+[[:space:]]*|-[CghpTu][[:space:]=]+[[:graph:]]+[[:space:]]+|--)*Sudo flags — both boolean stacks (-Eis) and value flags (-u root, -g wheel); -- terminator
([\\\"\']*env[\\\"\']*[[:space:]]+(-[iv]+[[:space:]]*|-[PSu][[:space:]=]+[[:graph:]]+[[:space:]]+|--)*)*An optional env wrapper between sudo and the real command, with its own flag set
([[:graph:]]+=[[:graph:]]+[[:space:]]+)*Var assignments between sudo/env and the real command
(.*)$The actual command and its args (preserved as $match[-1])

The regex requires (...)+ on the sudo block so at least one sudo invocation must match for the strip path to fire. This is why the toggle never false-positive-strips a non-sudo command, even one that happens to contain literal whitespace and var-assignments.

// SUDO FLAGS COVERED

ClassFlagsSpec
Boolean (stackable)-A -B -b -E -H -n -P -S -i -sPer sudo(8): no-arg flags that can be stacked (-Eis)
Value-bearing-C -g -h -p -T -uTake an argument: -u root, -g wheel, -p 'prompt'
Option terminator--End-of-options marker before the command word

~EXAMPLE TRANSFORMS

Toggle behaviour across the cases the regex is built to cover. Each row is one widget invocation, before → after.

BeforeAfter
apt updatesudo apt update
sudo apt updateapt update
(empty)sudo <previous fc -ln -1 entry>
sudo -u root apt updateapt update
sudo -Eis bashbash
sudo -- apt updateapt update
FOO=bar sudo apt updateapt update
sudo env -i bashbash
sudo env FOO=bar apt updateapt update
command sudo apt updateapt update
builtin command sudo apt updateapt update
"sudo" apt updateapt update
(with ZPWR_SUDO_CMD=doas) apt updatedoas apt update

!LBUFFER VS RBUFFER

ZLE splits the command line at the cursor: text to the left is in $LBUFFER, text to the right is in $RBUFFER. The widget runs the strip regex against $LBUFFER first, then falls through to $RBUFFER on no match. Toggling works at any cursor position.

Cursor after sudo

Common case: typed sudo apt update, cursor at the end. $LBUFFER is the whole line; LBUFFER regex matches; the strip fires on the left half. $RBUFFER stays empty.

Cursor inside sudo flags

User typed sudo -u root apt update, then hit ^A + a few arrows to land inside the flag block. $LBUFFER ends mid-sudo (no match); $RBUFFER contains the trailing chunk including sudo — nope. The fallthrough kicks in and prepends another sudo — arguably wrong, but matches the user's intent "I'm adding privilege escalation." Place cursor at start or end for clean toggle.

Cursor at line start

Just typed something, hit ^A. $LBUFFER empty; $RBUFFER is the whole line. RBUFFER regex matches; the strip fires on the right half. Cursor stays at column 0.

Toggle preserves position

Because the rewrite happens on whichever side matched (not the whole BUFFER), the cursor's logical position is unchanged. Hit the chord twice → back to the original line, character-for-character, cursor at the same column.


*TEST COVERAGE

101 zunit @test cases across 6 test files. The heaviest is t-sudo-command-line.zsh at 81 cases — every regex branch is pinned by at least one before/after pair plus a no-op pair (calling the widget twice should round-trip). The remaining 5 files pin structural contracts: widget registration, env-var defaults, idempotent re-source, entrypoint stem, syntax cleanliness.

Test file@testPins
tests/t-sudo-command-line.zsh81Every regex branch: empty BUFFER + history recall; prepend on plain command; strip on plain sudo; strip on sudo with stacked flags; strip on sudo with value flag; strip on var-prefixed sudo; strip on env-wrapped sudo; strip on builtin/command-wrapped sudo; strip on quoted sudo; round-trip preservation; LBUFFER vs RBUFFER coverage; custom ZPWR_SUDO_CMD; alternation in ZPWR_SUDO_REGEX
tests/t-contract2.zsh6zle -N sudo-command-line registers the widget; widget name appears in $widgets
tests/t-contract3.zsh5ZPWR_SUDO_CMD + ZPWR_SUDO_REGEX default to sudo when unset; existing values are not clobbered on re-source
tests/t-contract4.zsh5Entrypoint stem (sudo.plugin.zsh) matches plugin directory; idempotent re-source
tests/t-contract.zsh3Entrypoint parses cleanly under zsh -n; every _* completion file (vacuously zero) starts with #compdef
tests/t-syntax.zsh1Entrypoint parses under zsh -n
6 zunit files101+ 21 .sh doc-hygiene gates

?KEY DESIGN DECISIONS

Each call-out is a decision the implementation could have gone either way on, with the rationale for the path taken.

Two regex passes, not one

The widget runs the strip regex twice: once against $LBUFFER, once against $RBUFFER. Single-pass against the whole $BUFFER would lose cursor position; the split-and-test pattern is what makes the toggle feel like a true in-place edit.

One regex, not seven small ones

The 700-character pattern handles every case in one match. Breaking it into per-case regexes would mean ordering decisions (which case wins on ambiguity?) and would duplicate the leading [[:space:]]* + var-assignment + builtin/command framing across every variant.

Decoupled CMD and REGEX env vars

The prepend string is one var; the strip pattern is another. Lets the strip side support alternation ((sudo|doas)) while the prepend side picks one canonical tool. Most users set both to the same string; power users get the flexibility.

No bundled keybinding

The plugin registers the widget but does not bind a key. The user picks their chord. Stock oh-my-zsh sudo binds Esc Esc; this plugin doesn't force that choice because Esc Esc can conflict with vi-mode users hitting double-Esc to leave insert mode.

builtin fc -ln -1 for history recall

fc -ln -1 prints the most recent history entry with no leading line number and no trailing newline — exactly the shape needed for direct LBUFFER assignment. builtin guards against user aliasing of fc.

Var-assignment support

FOO=bar sudo cmd is a real pattern (env-vars-for-sudo). The regex preserves the assignments through the strip so toggling on FOO=bar sudo cmd gives FOO=bar cmd — not cmd. The user keeps their env intent.

Quoted sudo support

Each occurrence of the sudo command is wrapped in [\\\"\']* — matches bare, backslash-escaped, double-quoted, and single-quoted sudo names. Real scripts run "sudo" apt update for various reasons; the toggle handles all of them.

Single-file plugin

No autoload, no completions, no extra files. The widget body is small enough that splitting into autoload/sudo-command-line would add ceremony without value. One file, one widget, one fn.


.STRATEGIC POSITION

Smallest plugin in the stack by LOC, and arguably the highest invocations-per-day. Privilege escalation comes up dozens of times in a sysadmin shell session; a one-chord toggle saves the entire "up-arrow, home, type sudo space, end, enter" dance every single time.

Forgot sudo

Ran apt update, got Permission denied. Hit the chord on empty BUFFER → sudo apt update. Hit Enter.

Wrong sudo flag

Typed sudo -u nobody apt update and meant sudo apt update. Hit the chord (strip) + chord (re-prepend) → clean sudo apt update.

Cross-tool compat

Configured for doas on an OpenBSD box and sudo on Linux. Same chord, same UX, no muscle-memory tax across machines.

Plugin stack hub

One of 5 plugins under MenkeTechnologiesMeta. The smallest by LOC but the canonical example of "one fn, one chord, BUFFER rewrite" — the same shape as zsh-sed-sub, zsh-expand, and zsh-git-acp.


+COMPAT

Hard deps: zsh 5.x+ with ZLE; no external tool deps — the widget runs entirely within zsh's match engine. builtin fc is a core zsh builtin, always available. Compat with doas, please, run0, pkexec, or any other prepend-style escalation tool by setting ZPWR_SUDO_CMD + ZPWR_SUDO_REGEX. No OS-specific behaviour — identical on macOS, Linux, BSD, WSL.