cljsh
Clojure at the zsh prompt: type ( on an empty prompt and you get a rebel-readline line
(highlighting, completion, inline docs) evaluated in a Clojure process that belongs to the tab.
zsh stays the shell, and the Clojure code can see and change it: its directory, its
environment, and commands run in the real shell with your aliases and functions.
A Clojure form can also be an argument of an ordinary command, invoice (+ 1234 5555) leg,
and Clojure code can read zsh variables as $name.
Status. A personal project. It has only been run on macOS, with zsh 5.9 in iTerm under
oh-my-zsh and powerlevel10k; nothing has been tried on Linux or in other terminals. It hooks
into the zsh line editor, including a check on every line you enter, so try it in one tab
first (source <path to cljsh>/cljsh.plugin.zsh) before adding it to ~/.zshrc, and read
Known limits. CLJSH_INLINE=0 turns the forms-as-arguments part off.
Install
Needs zsh, the Clojure CLI and Java 22 or later. Add one line to ~/.zshrc, or, with
oh-my-zsh, link the folder in as a custom plugin and add cljsh to plugins=(…):
source <path to cljsh>/cljsh.plugin.zsh # in ~/.zshrc
ln -s <path to cljsh> "$ZSH_CUSTOM/plugins/cljsh" # or this, for oh-my-zsh
Each tab’s process starts on its first ( or inline form (about 1.5 s), uses about 130 MB
after a first visit and 200 MB after a heavy one, and stops when the tab’s shell exits.
exec zsh (as omz reload does) keeps it, with its definitions.
Using it
One ( opens one line; it is evaluated, results print, and zsh’s prompt returns. Definitions,
the namespace and *1/*2/*3/*e carry over to the next line. These are referred into user:
| Form | Does | Returns |
|---|---|---|
(sh ls -la) |
runs in the real shell, attached to the terminal; cd, export and the like persist |
exit status |
(sh-str git rev-parse HEAD) |
captures standard output | string, trailing newline trimmed |
(sh-lines ls) |
captures standard output | vector of lines |
(sh-ok test -f deps.edn) |
runs quietly | true if exit status is 0 |
(cd "src") |
changes the real shell’s directory, and the server’s | the new directory |
(setenv "K" "v") |
exports in the real shell and updates the snapshot | the value |
(getenv "K") / (getenv) |
reads the snapshot | string / map |
In the sh forms, symbols, keywords and numbers are literal text (ls, -la, *.txt); a
string goes through as written ((sh "ls ~/foo | head -3")); a list or vector is evaluated
and its value passed as a quoted word, a sequence as several words ((sh echo (+ 1 2))).
sh*, sh-str*, sh-lines* and sh-ok* take one command string, for use from other code.
(path "a" "b") resolves against the shell’s directory. At the zsh prompt,
cljsh-eval '(+ 1 2)' evaluates in the tab’s process without the editor.
- Leaving a line without evaluating it: Ctrl-C, Ctrl-D, Enter on a blank line, or
Backspace when the line holds only the
(. While you edit, Ctrl-C is a key read in order with the others, so keys typed before the editor appears are handled as typed, and Ctrl-V Ctrl-C inserts a literal^C. - Ctrl-C during an evaluation interrupts it; during a shell command it ends the command
and the evaluation around it. One typed after Enter, before the evaluation has started,
cancels it (
Interrupted.). If the evaluation ignores it (a tight loop), a second Ctrl-C a second or more later kills the tab’s process: its definitions are lost, and the next(starts a fresh one.
Forms as arguments
A Clojure form can be an argument of any zsh command typed at the prompt:
invoice (+ 1234 5555) leg # runs: invoice 6789 leg
The form is evaluated in the tab’s Clojure process, so definitions from ( lines are there.
A word counts as a form when it is a whole word in argument position (after the command
word, not an assignment’s value or a redirection’s target) that starts with ( after a
space and ends at its matching ), found by Clojure’s rules for strings and characters. A
parenthesised word with no unquoted space inside that holds a glob character or a quote
((foo|bar), (*.txt), ("a b")), and anything with text right after it
((foo|bar)*.txt, *(.)), stays a zsh pattern. A parenthesised single name such as
(README) or (now) is a call: plain zsh reads it as glob qualifiers and gives an error
(unless bare_glob_qual is off), so no line that worked before changes. To pass
parentheses literally, quote or escape them as in plain zsh: '(+ 1 2)', \(x\).
| The form returns | The command receives |
|---|---|
| a string | that string as one argument, exactly (spaces, newlines, glob characters, the empty string) |
nil |
no argument |
| any other single value (number, keyword, symbol, boolean, character, file, path, object) | one argument: its str |
a vector, list, sequence or set, a Java array or any other java.util.Collection |
one argument per element, by these rules (a nil element gives none); a nested collection, array or map element as its pr-str |
a map (a Clojure map or any java.util.Map) |
one argument: its pr-str |
So (.split "a,b" ",") gives the two arguments a and b. Values are passed in full
whatever *print-length* and *print-level* are.
What the form prints goes to the terminal, not into the arguments. A form is evaluated when
its command runs, not when Enter is pressed, so
cd reports && invoice (count (sh-lines ls)) leg counts the files in reports, and
for f in *.txt; do echo (count $f); done evaluates once per file. It runs in a subshell,
so (cd …) or (setenv …) inside one does not change your shell; use a ( line for that.
If a form throws, its error is shown, followed by zsh’s own line zsh: cljsh: form failed,
and the command it is an argument of never runs. The rest of the line is abandoned too, as
with Ctrl-C, wherever the form is in it: in a loop or function, a pipeline segment
(gen (bad) | sort > out && deploy out deploys nothing) or a subshell. A form in a
background job (cmd (f) &) ends only that job, so what you are typing at the prompt is
kept. Ctrl-C during a slow form interrupts it the same way. The line on screen and in
history is the one you typed.
zsh variables
In Clojure code (inline forms, ( lines and cljsh-eval), $name reads the zsh variable
name, as (getvar "name") does. A scalar is a string, an integer or float a number, an
array a vector of strings, an associative array a map of strings, so $path is a vector and
$PATH a string. A variable that is not set is nil: (or $EDITOR "vi"). One declared but
not assigned (typeset x, local x) is set, to "" (an integer to 0, an array to []),
unless the option typeset_to_unset is on. Unexported variables, function locals and loop
variables are seen: the value comes from the shell running the code, read from inside
cljsh’s own functions. So $argv and $ARGC are an error (they would be cljsh’s
positional parameters, not your function’s: copy them first, args=("$@")), and variables
that describe the running function or shell, such as $funcstack, $ZSH_SUBSHELL,
$status and $REPLY, describe cljsh’s. A $name that is a Clojure var or local keeps
that meaning, and inside the sh forms $name is left for zsh to expand. Each $name is
read once per top-level form, before it runs: a function defined with $name in its body
keeps the value from when it was defined, while (getvar "name") in the body reads it at
each call. For the same reason a top-level (do (defmacro m …) (m $a)) that uses $name is
compiled as one form, so the macro is not yet defined where it is used; split it into two
forms. $name means a zsh variable only while a shell is listening: in ~/.cljshrc it is an
ordinary Clojure symbol, as (let [$x 1] $x) is everywhere.
Settings
CLJSH_PREWARM=1starts the process when the shell starts instead of on the first(.CLJSH_JVM_OPTSreplaces the JVM options; the default is-XX:+UseSerialGC -Xmx1g -XX:TieredStopAtLevel=1 -Xms16m -XX:MaxNewSize=32m -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=30.-XX:TieredStopAtLevel=1keeps the footprint small at the cost of speed in long computations; leave it out of your own value to trade back.CLJSH_START_TIMEOUTis how many seconds to wait for the process to start (default 30).CLJSH_RCnames the startup file (default~/.cljshrc).CLJSH_INLINE=0turns forms as arguments off; it is read at each Enter.
~/.cljshrc is Clojure loaded into user when the process starts. What it prints, and any
error, shows at the start of the first line; sh, cd and setenv in it throw (no shell is
listening yet). The classpath is cljsh’s plus your ~/.clojure/deps.edn, and
(add-lib 'hiccup/hiccup) adds a library to the running process (the first time, it needs
network access to fetch it). History: ${XDG_STATE_HOME:-~/.local/state}/cljsh/history.
Known limits
- Only a typed
(opens a line: pasted text stays zsh. For a literal(at the start of a zsh line, type a space first, or Ctrl-V(. Withhist_ignore_space(oh-my-zsh sets it) the space also keeps that line out of your history; Ctrl-V(does not. - The JVM keeps its startup directory for
File.getAbsolutePathandPath.toAbsolutePath; relative reads, writes and child processes do follow the shell. Usecljsh.core/path. - Keys typed during a long evaluation go to Clojure (or, past a limit, are dropped), not to the next zsh prompt.
- Ctrl-D leaves the line even when it has text.
- In the
shforms Clojure reads numbers before cljsh sees them:(sh chmod 0644 f)runschmod 420 f, and1.50becomes1.5. Write such arguments as strings ("0644"). - In the
shforms a map or set literal is evaluated and passed as one quoted word (a set as one word per element); an unsupported form such as a regex literal is an error. cljsh-evalis a function of the interactive shell only: scripts cannot use it.- Window resizes reach the editor within about half a second.
Forms as arguments:
- Only lines that pass through the line editor are rewritten. The up arrow works, and
!!withhist_verify(oh-my-zsh sets it);r,fc -s,!!withouthist_verifyand a form inside an alias’s definition are not, and zsh reports its usual pattern error. - No forms inside quotes,
$(…), backticks,[[ … ]]or(( … )). A line with a here-document, or withcaseor a#comment inside$(…)or a parenthesised group, is left alone as a whole, and so is a command longer than 1000 characters (all its lines together), which would take the scan too long. - A command run through an alias that ends in a reserved word or precommand modifier
(
alias t=time) or in a space (alias s='sudo ') is left alone: its parentheses are zsh’s. - Forms inside a function body are rewritten when the function is defined with a brace body
(
f() { cmd (form) }), not for a parenthesised body or a body without braces. - With
setopt noglob, or for a command run throughnoglob(directly or through an alias such asfind='noglob find'), parenthesised words are passed literally and nothing is evaluated. - Forms that run at the same time share the process’s one current directory: overlapping
forms started from different directories, as in
(cd x; cmd (f)) & cmd (g), can resolve relative paths against the wrong one. - zsh runs a rewritten command, and that is what these see, not the line you typed:
preexechooks (the terminal tab title, for one), background-job notices,functionsandwhichfor a function defined at the prompt, otherzshaddhistoryhooks (atuin, histdb), and the up arrow right after a line kept out of history by a leading space (hist_ignore_space). With history expansion on the line and nohist_verify(echo !$ (+ 1 2)), zsh prints the expanded rewritten line, and the history entry keeps the!$as typed, which expands differently when recalled. - The history entry of a line with a form is made when its command finishes, or, if the
shell ends first (
exit, or the tab closed while the command runs), as it ends; a line that replaces the shell (exec …) gets none. Withshare_historyorinc_append_historythe entry reaches the history file (and, withshare_history, other tabs) with this tab’s next command, or when the shell exits; without them, as every entry does, when the shell exits.hist_ignore_all_dupsapplies to lines with a form;hist_ignore_dupsalone does not, so such a line typed twice in a row gives two entries. - The typed line stays on screen because cljsh’s
zle-line-finishhook runs after the others: each time a line starts, cljsh moves its hook back to the end of those added withadd-zle-hook-widget. A hook added while the line is being edited can still redraw that line as the rewritten text; the command runs correctly all the same. A plugin that replaces thezle-line-initorzle-line-finishwidget itself (zle -N) after cljsh is loaded can bring that redraw back for every line, and replacingzle-line-finishwithout chaining to the previous widget stops inline forms from being evaluated at all. Loading cljsh last, as the install line does, avoids both. - An INT trap of yours (
TRAPINT,trap … INT) can let the rest of the line run after a form failed in a pipeline segment or a subshell, since abandoning the line then takes an interrupt; so doessetopt no_monitor, without which a foreground segment cannot be told from a background job. The command with the failed form still never runs.
Tests
clojure -M:test
CLJSH_E2E_REAL=1 python3 -m unittest discover -s test/e2e -v
The end-to-end tests drive zsh in a pseudo-terminal. CLJSH_E2E_REAL=1 adds a run with your
own startup files, which write their usual caches; only your zsh history is kept apart.
License
Copyright © 2026 Jonathan Huston
Distributed under the Eclipse Public License, version 1.0. See LICENSE.