Baddcafe zsh theme — keeping the prompt out of the way

My Baddcafe theme started with the information I wanted in front of me: working directory, Git state, a clock, CPU, memory, battery and IP addresses. The harder part was making that information coexist with the shell I was trying to use.

A slow Git repository should not delay the first prompt. A public-IP lookup should not hold up typing. A clock should not erase a mouse selection every second. Reloading .zshrc should not leave two collectors publishing competing answers.

The implementation is one Oh My Zsh theme file plus an installer. This post follows the mechanisms in that file; it does not claim measured speedups or identical rendering across every terminal.

Separate collection from drawing

The foreground prompt does not need to collect every metric when it renders. It needs the latest available snapshot:

background collector → snapshot file → foreground read → prompt
Git child process    → pipe          → ZLE callback    → Git segment
alarm tick           → clock update, if the line editor can safely redraw

On Linux, the CPU and memory collectors read /proc using shell builtins. Battery capacity comes from /sys. Some other collectors run external commands; on macOS, CPU and memory collection use different tools. Moving work into a background process does not make that work free. It takes it out of the foreground redraw path.

Each metric has its own interval. Defaults from theme/baddcafe.zsh-theme:

: ${BADDCAFE_INTERVAL_CPU:=2}
: ${BADDCAFE_INTERVAL_MEM:=2}
: ${BADDCAFE_INTERVAL_BAT:=30}
: ${BADDCAFE_INTERVAL_LOCALIP:=60}
: ${BADDCAFE_INTERVAL_GLOBALIP:=3600}

The collector wakes more frequently than the slowest metric needs updating. It compares timestamps before invoking each collector, rather than running every command on every tick.

That is a freshness policy. A cached public address can be stale after a network change, and a local-IP collector is not a complete routing diagnosis. The prompt is an overview, not an authoritative monitoring system.

CPU usage is a difference, not one counter

The Linux CPU collector reads the first line of /proc/stat. The counters accumulate CPU time, so a single read cannot describe utilization over the last two seconds.

After summing the selected fields, the implementation computes a delta:

local -i idle=${f[5]:-0}
local -i dt=$(( total - _bc_cpu_prev_total )) di=$(( idle - _bc_cpu_prev_idle ))
_bc_cpu_prev_total=$total
_bc_cpu_prev_idle=$idle
(( dt > 0 )) || return
printf -v _bc_v_cpu '%.1f' $(( 100.0 * (dt - di) / dt ))

This is an excerpt: f and total are built earlier in the function. The collector primes the counters and waits before publishing an interval result.

The definition of idle matters. This implementation subtracts the idle field and leaves I/O wait in the non-idle portion, so it should not be described as precisely matching every system monitor's CPU percentage. The macOS path sums process CPU percentages, which has different semantics and can exceed 100 on a multicore machine. The same label is not proof of identical measurements.

Publish a snapshot instead of half a line

The collector renders the stats string and computes its expected display width. It writes both into a temporary file before renaming that file over the current snapshot:

if print -rl -- $line $REPLY_W > $out.new 2>/dev/null; then
    zf_mv -f -- $out.new $out 2>/dev/null
    last_line=$line
    last_w=REPLY_W
fi

This shortened block omits the shared-cache seed write inside the conditional. The file has two lines: rendered content, then column count. Keeping them in one snapshot prevents the foreground from combining a new string with an old width.

Rename within the same filesystem provides the publication boundary: a reader opening the snapshot sees the previous file or its replacement, rather than an in-progress write. This is an ephemeral UI cache, not a crash-durable journal or a security boundary. The current implementation also needs stronger handling if a rename fails; the excerpt updates its remembered state without checking that command's result.

A per-shell snapshot avoids making every prompt wait on the collector. A shared cache seeds the next shell with an immediate, potentially stale display until its own collector publishes fresh values.

Reloading the shell configuration is a lifecycle event

The snapshot name includes the user ID and shell PID. That isolates ordinary shell sessions, but re-sourcing .zshrc happens inside the same process. An exec zsh can retain the PID too.

The collector therefore checks an ownership token:

owner=
[[ -r $out.owner ]] && IFS= read -r owner < $out.owner 2>/dev/null
[[ $owner == $token ]] || return 0

The newly started worker publishes a token, and an older worker exits when it next observes a mismatch. The script also tracks its worker PID for explicit cleanup and registers a zshexit hook.

This is a practical lifecycle mechanism, not a transactional lock. The check and subsequent write are separate operations, so it cannot prove that a worker replaced immediately after its check will never finish one more publication. It does make ownership and shutdown visible instead of relying on old processes to disappear by accident.

Git status should arrive after the prompt

Git status can be expensive in a large working tree. The theme runs it in a child and watches the child's output pipe through ZLE. The async branch of _bc_precmd contains:

if exec {_bc_git_fd}< <( _bc_git_bg ); then
    zle -F $_bc_git_fd _bc_git_callback
else
    _bc_git_fd=0
fi

The first prompt can render while the child computes the segment. Its response includes the display width and segment text on one line. The ZLE file-descriptor watcher lets the parent receive the result without polling Git synchronously. The callback reads it with IFS= so leading/trailing spaces survive, closes the watcher, and redraws only when the segment changed.

Before starting another computation, the theme unregisters and closes the old descriptor. Changing directories also clears the previous Git segment so the new directory does not initially display another repository's branch.

This does not eliminate Git processes: it starts background Git work from precmd. The narrower claim is that async mode avoids waiting for that work before the initial prompt. BADDCAFE_GIT_ASYNC=0 deliberately switches back to synchronous computation, and BADDCAFE_GIT_UNTRACKED=0 can omit the untracked scan.

A redraw can destroy a selection

The clock originally made full redraws tempting. Advance the time, call zle reset-prompt, done.

But rewriting the prompt can invalidate a terminal's mouse selection. If the only change is one clock value, redrawing the path, Git segment and command line is unnecessary screen activity.

The current implementation tries to repaint only the clock/stat line. It tracks terminal columns, stats width, Git width, path length and cursor position. Before doing manual cursor movement it rejects cases it cannot measure safely. Selected guards from _bc_clock_paint:

(( BADDCAFE_INPLACE_CLOCK )) || return 1
(( _bc_sysinfo_w > 0 )) || return 1

local -i cols=COLUMNS
(( cols > 40 )) || return 1

[[ $PWD != *[^[:ascii:]]* ]] || return 1
[[ $BUFFER != *[^[:ascii:]]* ]] || return 1
[[ $BUFFER != *$'\n'* ]] || return 1

There are additional guards for wrapping, right-margin positions and changed geometry. If they fail, the alarm handler falls back to ZLE's full redraw. Selecting the clock line itself can still be affected, and terminal behavior varies; this is not a universal selection-preservation guarantee.

The alarm handler also checks whether the line editor is active and whether completion/search widgets own the display:

TRAPALRM() {
    zle || return
    _bc_zle_busy && return
    _bc_tick
    _bc_clock_paint && return
    zle reset-prompt
}

Testing the zle option is insufficient: that option describes shell configuration, while calling the builtin tests whether the editor is active at that point. _bc_zle_busy checks both $WIDGET and $LASTWIDGET, because an alarm can arrive between widget calls.

Character count is not terminal width

A prompt contains invisible color escapes, ordinary text, and glyphs whose terminal width can vary. If the shell and terminal disagree on wrapping, a repaint can target the wrong row.

The theme supplies explicit width hints for its emoji:

_BC_E_CLK='%2{🕰️%}'
_BC_E_CPU='%2{⚙️%}'

The %2{...%} wrapper tells zsh to account for two display columns, using the width accounting described in prompt expansion. It does not force the terminal to draw that glyph at that width. Font, terminal and Unicode-width behavior must agree with the hint; replacing a symbol means reviewing its width too.

Dynamic metric values also escape percent signs before prompt expansion. Otherwise a value containing % could accidentally be interpreted as prompt formatting. The width is calculated before the formatting escapes are mixed into the rendered string.

Installation should be reversible

The installer supports install, update and uninstall, respects ZDOTDIR and ZSH_CUSTOM, and backs up the shell configuration before changing it. It brackets its own edits with markers:

BEGIN_MARK="# >>> baddcafe theme >>>"
END_MARK="# <<< baddcafe theme <<<"
DISABLED="#baddcafe-disabled# "

Uninstall strips that block and re-enables the theme assignments it disabled. It avoids restoring an entire old .zshrc over unrelated edits made after installation. The new ZSH_THEME assignment must appear before Oh My Zsh is sourced, because that is when the theme choice is read.

The default download follows the repository's main branch. That is convenient for updates, but it is a moving version rather than a reproducible installation. The installer exposes branch/source overrides; a pinned revision is the more explicit choice when reproducibility matters.

What I would verify in a terminal

Syntax checks can reject broken shell syntax. They cannot establish correct cursor placement or mouse-selection behavior. The useful interactive cases are:

  • A slow repository: the initial prompt appears before Git finishes.
  • Directory changes: the previous repository's segment disappears.
  • Tab completion and history search: clock updates do not disrupt the editor-owned display.
  • Long paths, narrow windows, resize, Unicode and multiline input: uncertain geometry falls back safely.
  • Repeated .zshrc reloads: old workers stop and the current snapshot continues updating.
  • Offline public-IP lookup: input stays responsive while the collector times out.

The tunables make those behaviors inspectable: disable the ticker with BADDCAFE_TICK=0, disable in-place clock painting with BADDCAFE_INPLACE_CLOCK=0, or disable public-IP collection with BADDCAFE_GLOBALIP=0. Set them before loading the theme.

What started as a visual shell customization became an exercise in latency, asynchronous results and ownership of a shared screen. The useful design choice was to make the prompt consume snapshots, then be conservative about when and how it redraws.