Cheat sheet

One page of everything: what goes in a fence, in the front matter and on the command line, and which key does what in mdsh -i and the desktop app. Each row says only what a thing is; the other pages say how it behaves.

Command line

CommandDoes
mdsh doc.md [args…]Run every block, print the markdown with output under each block. Same as mdsh run doc.md; #!/usr/bin/env mdsh works. args reach blocks as $1, $2…
mdsh -w doc.mdRun and write the output back into the file
mdsh -o out.md doc.mdLike -w, into out.md; doc.md is untouched
mdsh -n doc.md (--no-run)Print with the output saved by -w; nothing runs. -n -o view.md saves that printout
mdsh -n --history doc.mdAlso print each block’s earlier runs, kept by history=N, under its output; --html and --pdf take it too
mdsh --hide-code doc.mdProse and output only
mdsh --hide-output doc.mdProse and code only; with --hide-code too, prose only and nothing runs
mdsh --only build doc.mdRun that block, plus the earlier blocks in its env chain
mdsh --yes doc.mdRun confirm blocks and depends= blocks without asking
mdsh --step doc.mdAsk before every block, as if each were marked confirm
mdsh --stop-on-error doc.mdStop at the first failing block
mdsh --expose DEBUG doc.mdLet {{$DEBUG}} read your environment; repeatable or comma-separated. MDSH_EXPOSE=A,B does the same
mdsh --source defs.zsh doc.mdSource a file into every shell before its first block; repeatable; a pipe works
mdsh --audit run.jsonl doc.mdAlso write a JSON Lines log of the run
mdsh --allow-outside doc.mdLet includes, out= files and report images reach outside the document’s folder, or hidden files (.env, .git) in it; only for documents you trust
mdsh --pdf doc.pdf doc.mdWrite what would be printed as a PDF (- for stdout); the hide flags, --only and --step apply
mdsh --html doc.html doc.mdThe same as a standalone HTML page; not with --pdf
mdsh --show-secrets --pdf out.pdf doc.mdPut secret blocks’ code and output in the report; without it they read (secret)
mdsh --color=never doc.mdNo styling on a terminal; --no-color and NO_COLOR too (auto, always, never)
mdsh -i doc.mdThe terminal UI; --autosave saves after every block that runs; --history-reuse runs a command typed in History again in its #history-N block, keeping earlier runs
mdsh -i --interactive-shell doc.mdHistory’s shell runs interactively, reading your rc files, and its pane is a terminal: vim, ctrl+z, fg and jobs work, ctrl+g gives the keys back; --login-shell starts it as a login shell (experimental)
mdsh -i [folder]A start screen listing the markdown files under this folder, or that one
mdsh --serve [doc.md | folder]The desktop app’s notebook in a web browser, at 127.0.0.1:8080; --serve=host:port listens elsewhere. Anyone with the printed address can run commands as you. Only in an mdsh built with -tags serve
mdsh --serve=stdio doc.mdThe same notebook to the program that started mdsh, such as an editor plugin, as JSON lines on stdin and stdout
mdsh - < doc.mdRead the document from stdin
mdsh completion bash|zshA completion script: flags, .md files and, after --only, block ids
mdsh lspA language server on stdin and stdout: completes and explains fence attributes, flags mistakes
mdsh ctl …From inside a block, talk to the run (below)
mdsh --versionThe version

Exit status: 0, 1 when any block failed, 2 on an error such as a bad flag or file.

VariableDoes
MDSH_EXPOSE=A,BVariables {{$A}} may read, as --expose
NO_COLORNo styling on a terminal, and no image previews in mdsh -i
MDSH_NOTIFY=off|bell|osc9|osc99|osc777How mdsh -i asks the terminal for a desktop notification when a question waits or a long run ends and you have looked away; by default it picks by terminal
MDSH_STARTUP_TRACE=1mdsh-gui prints when it reaches each point of starting up

On a terminal, mdsh doc.md and mdsh -i tell it what they are doing: the file in the tab’s title, marked [50%] (from mdsh ctl status --step), [running], [waiting], [failed] or [done]; a progress bar on the tab where the terminal draws one (OSC 9;4); and their state by the Program Status Protocol (OSC 7501). A tty block that retitles or recolours the terminal gets it put back.

mdsh ctl works only in a block mdsh is running:

CommandDoes
mdsh ctl set [--secret] NAME VALUESet $MDSH_VAR_NAME for the blocks after this one; - reads the value from stdin; --secret has mdsh-gui blur output that names it
mdsh ctl unset NAMERemove a variable set made
mdsh ctl get NAMEPrint $MDSH_VAR_NAME as it is now
mdsh ctl ask [--choice a,b] [--default V] [--secret] QUESTIONAsk for text and print the answer
mdsh ctl confirm [--default yes|no] QUESTIONAsk yes or no; the exit code is the answer
mdsh ctl status [--step N --of M] TEXTShow progress for this block
mdsh ctl helpList these. Exit codes: 0 done or yes, 1 no, 2 refused, 3 not under mdsh, 4 no answer

mdsh-gui [flags] [file.md [args…] | folder] takes --source FILE, --only ID, --step, --stop-on-error, --serve=stdio (once Settings › Shell turns it on) and --version; on Linux the AppImage runs the command line tool when started with --cli first.

Questions a run asks

PromptAnswers
Run this block? (confirm, --step, step: true)r run · k skip · o skip this and every later block with saved output · s or enter stop
Run build first? (depends=)r run · k go on without it · s or enter stop

With no terminal the run stops at a question unless --yes answers it.

Fence attributes

Attributes sit in {…} after the language: ```sh {#build env=ci confirm="Deploy?"}. Every sh and zsh block runs, and an http block makes its request; other languages are left alone. Unknown attributes are kept as written.

AttributeDoes
#idThe block’s name, for output, placeholders, depends= and --only. Saving gives an unnamed block block-<uuid>
skipDon’t run (picking the block by hand in mdsh -i or mdsh-gui still runs it)
run=CONDRun only if the condition holds; run=once runs it only while it has no output
show=CONDPrint the code only if the condition holds
show-output=CONDPrint the output only if the condition holds
show-stderr[=COND]Show stderr always, or if the condition holds; by default only when the block fails
collapse[=COND]In mdsh-gui, open with the code folded to one line
collapse-output[=COND]In mdsh-gui, open with the output folded to one line; output past 25 lines (front matter fold_output:) folds unless collapse-output=false
nosaveSaving keeps what the file holds: the output, a textbox’s text or a choice’s picks live in the session only. On an output fence, just that fence
secretThe code and output hold a secret: mdsh-gui and mdsh -i mask them until shown, and as with nosave the output isn’t saved
linksMake http:, https: and mailto: addresses in the output clickable in mdsh-gui and mdsh -i
env=NAMERun in a named sub-env, a shell of its own; a/b stacks b on a
share=A,BExported variables a new sub-env gets from its parent, besides the base set. ... or * all, -NAME drops one, empty just the base set. Default: front matter env.share, else all
wd=DIRRun in DIR (relative to the document, ~/ is home), then go back to where the shell was, even if the block fails or is stopped
on_error=stop|continueStop the run if this block fails, or go on. Default: front matter on_error
depends=A,BBlocks to run first, in order; each one that hasn’t run this session is asked about
alwaysAs a dependency, run again each time a block that depends on it runs
confirm[="Question?"]Ask before running, with this question if given
timeout=30sInterrupt the block after this long and stop the run; its shell stays. A background block is killed alone
backgroundStart the block and go on to the next; the run waits for it at the end. $MDSH_BG_<id> holds its PID for wait. With tty, it runs on a terminal of its own in its card (mdsh-gui, mdsh -i, --serve), such as an editor open while other blocks run, and isn’t waited for
ttyRun on a terminal, for docker run -it, ssh, an editor; the session is saved as an asciinema cast
frame=NWith tty, or on a cast fence, the frame still views show and the player opens at, from 1
out=textOutput goes in an output fence (the default)
out=markdownOutput is inserted as markdown, between <!-- mdsh:output for="id" --> and <!-- /mdsh:output -->
out=image[:path]Output is image bytes (PNG, JPEG, GIF, SVG), saved beside the file and linked
out=screenshot[:path]The text output drawn as a terminal-style image: SVG, or PNG when the path ends in .png
out=file[:path]stdout to a file (<doc>.assets/<id>.log); the output fence is an include of it, whose window attributes (match=, lines=…) you set and mdsh keeps
out=recording:pathWith tty, where the cast goes; a path ending in .gif links an animated GIF too
embed=inlineWith out=image or out=screenshot, a data URI instead of a file
rawOn an http block, save the response body as it came instead of pretty-printing JSON
history[=N]Keep the block’s N earlier runs under its output, newest first; bare, the front matter’s history, else 10

Paths default to <doc>.assets/<id>.<ext>; res://name is name in that folder.

Include blocks

```go {<include file=cmd/main.go from=10 to=24 number_on} fills the block with lines from a file on every run. It never runs, has no name and takes none of the attributes above.

AttributeDoes
<includeMarks the block as an include
file=PATHThe file, relative to the document; res://name is in its assets folder (required)
from=NFirst line, counting from 1 (default the first)
to=NLast line, inclusive (default the last)
number_onShow each line’s number in the file
match="RE"Start at the first line matching a Go regexp (not with from=/to=)
symbol=NAMEShow a Go func, method (T.M), type, const or var with its doc comment; other languages best effort, A.b for b inside A
comment=falseWith symbol=, leave out the doc comment
before=NAlso show N lines above the start
lines=NShow N lines from the start
until="RE"End at the first line from the start matching a regexp (not with lines=)

No match leaves the block empty with a warning; the run doesn’t fail.

Input blocks

A textbox fence is a box to type in; a choice fence lists its options as task items (- [x] prod). Both write what is picked back into the file on save.

AttributeOnDoes
var=NAMEbothBind the text, or the checked options one per line, to $MDSH_VAR_NAME for blocks and conditions
lines=NtextboxThe most lines it holds; 1 or less is one line
lines=fittextboxAny number of lines; mdsh-gui sizes the box to the text
mode=dropdown|radio|multichoicePick one from a list (default) or buttons, or check any number
placeholder="…"bothWhat an empty textbox, or a dropdown with nothing chosen, shows
nosave, secretbothAs above: what is typed stays in the session

Other fences and markers

Fence or lineDoes
```output {for=id exit=0 at=…}A block’s output, right under it; elsewhere, a copy mdsh refills on every run. at= is when the run started, shown as “3 mins ago”; stream=stderr is its stderr; history=K marks an earlier run, K back; nosave keeps that fence out of the file
<!-- mdsh:output for="id" --> … <!-- /mdsh:output -->The same for out=markdown and image output
```tape {for=id}Types the input for tty block id, in VHS commands: Type "…", Enter, Tab, Up…, Ctrl+X, Alt+X, Sleep 1s, Wait /regex/, Set TypingSpeed, WaitTimeout, WaitPattern. Double-quoted Type takes placeholders. Can be an include
```httpOne request: METHOD URL, headers, a blank line, the body; HTTP 200, then [Asserts] (jsonpath $.id == 1, header X contains y, status, body, regex, duration) and [Captures] (token: secret jsonpath $.token, read as {{#id/env(token)}}). {{#id/status}}, {{#id/json($.x)}} and {{#id/header(Name)}} read the response in prose and conditions. [QueryStringParams], [FormParams], [Options] (insecure, follow, timeout) and an @file body. env=, share=, tty, background and out= are errors on it
```castAn asciinema recording, played in mdsh-gui; frame=N opens it there
```d2, ```svgA diagram, a picture, drawn in mdsh-gui
- [ ] taskA task item mdsh-gui checks in the file when clicked; table cells starting with [ ] too
<!-- mdsh:if COND --> … <!-- mdsh:end -->Print the stretch only if the condition holds; sections nest. It hides but doesn’t stop blocks: gate them with run=
<!-- mdsh:collapse [COND] -->Under a heading: mdsh-gui opens the section folded
#!/usr/bin/env mdshOn the first line: chmod +x and run the file

Conditions and placeholders

FormMeans
{{#setup/env(NAME)}}The value NAME had right after block setup ran, exported or not
{{#setup/env(NAME):"world"}}The same, with the last value stored by -w so the file reads without running
{{$NAME}}NAME from the environment mdsh started in, if exposed with --expose or MDSH_EXPOSE; never saved. MDSH_ variables need no exposing
{{$?}}, {{#build/?}}The exit status of the last block that ran, or of block build
{{$err?}}, {{#build/err?}}The same statuses, read as true when non-zero
{{$ran?}}, {{#build/ran?}}Whether the last runnable block, or build, ran
{{$MDSH_VAR_name}}, {{$MDSH_MODE}}An input’s value; running, interactive or report

A condition is a placeholder without the :"…" part, negated with ! or compared with == or !=: run={{$DEBUG}}, show={{$ran?}}, run={{#detect/env(OS)}}==Linux, show-output={{$?}}!=0. true, false and (in run= only) once are conditions too. A bare value is true when set and not 0, false, no or off. In run=, {{$?}} is the previous block’s status; in show=, show-output= and show-stderr= it is the block’s own. Placeholders in code and inline code are left alone; interpolate: false turns them off in prose.

Front matter

Under an mdsh: key at the top of the file; every key is optional, and unknown ones are ignored.

---
title: Build notes
description: What this runbook does, for the start screens
tags: [ops, prod]
mdsh:
  shell: /bin/bash
  on_error: stop
  step: false
  interpolate: true
  show_stderr: false
  history: 10
  fold_output: 25
  terminal:
    cols: 100
    rows: 30
  http:
    secret_headers: [X-Session-Id]
  env:
    share: [..., -GITHUB_TOKEN]
    source: [~/.zsh_aliases, lib/helpers.sh]
---
KeyValuesDefaultDoes
shella POSIX shell or zsh/bin/sh, or zsh if any block is zshThe shell that runs every block, in every env
on_errorcontinue, stopcontinueWhether a failing block stops the run; a block’s on_error= and --stop-on-error override it
steptrue, falsefalseAsk before each block, as if every block were marked confirm
interpolatetrue, falsetrueFill in {{…}} placeholders in prose
show_stderrtrue, falseunsetShow every block’s stderr, or none; a block’s show-stderr overrides it
historya whole number10How many earlier runs a bare history on a block keeps
fold_outputa whole number25Output longer than this opens folded in mdsh-gui, and is what an out=file fence shows with no window; 0 turns both off
terminal.cols, terminal.rowscells, up to 1000 by 500fit the card, 24The size of the terminal mdsh-gui runs tty blocks on
http.secret_headersheader namesnoneResponse headers, besides Set-Cookie, Authorization, Proxy-Authorization, WWW-Authenticate and X-API-Key, that http blocks save as (secret)
env.sharenames, ..., -NAMEthe base setVariables from mdsh’s environment that reach the top-level shell, and the default share= for sub-envs
env.sourcefile pathsnoneFiles sourced into every shell before its first block; ~/ is home, other relative paths are from the document

The base set is PATH, HOME, USER, LOGNAME, SHELL, TERM, COLORTERM, LANG, LANGUAGE, LC_*, TZ, TMPDIR and, on macOS, __CF_USER_TEXT_ENCODING. title, description (else summary, else abstract) and tags are read by the start screens and the Front matter form, not by the run.

Front matter that doesn’t parse, such as title: Setup: first steps with its colon unquoted, doesn’t stop the file opening: mdsh-gui and mdsh -i show the error over it, and no block runs until it is fixed. When a colon in a value is why, they offer to quote it. mdsh FILE runs nothing and says why.

A .mdsh.yaml in a folder makes it a collection on mdsh-gui’s start screen: title, description, icon (an image in the folder or an emoji), color, background and tags.

Inside a block

NameIs
$1, $2…The arguments after the file name
$MDSH_BLOCK, $MDSH_FILE, $MDSH_DIRThe block’s id, the document’s path and folder
$MDSH_MODErunning from the command line, interactive in mdsh -i and mdsh-gui, report for --pdf and --html
$MDSH_VAR_nameA textbox or choice with var=name, or what mdsh ctl set set
$MDSH_BG_idThe PID of background block id (anything but letters, digits and _ becomes _), for wait
md_h1, md_h2, md_h3Print a heading
md_table [-F SEP] [-s N]TSV on stdin to a markdown table; -F splits as awk -F does, -s skips lines
md_codePrint a code block

Blocks without env= share one shell, so variables, functions and the working directory carry over. An exit ends the shell and the run. Every env starts in the document’s folder.

mdsh -i keys

? lists these in the app, greying out the ones that do nothing right now.

KeyDoes
j/k, ↓/↑, tabNext or previous block
g/GFirst or last block
space, pgdn / pgup, ctrl+bPage down / up
ctrl+d / ctrl+uHalf a page down / up
enter, rRun the block; on a block running in the background, stop it
aRun from this block to the end
sRun the section the block is in
i, :Type a new sh block and run it; esc cancels
hHistory: a shell along the bottom whose commands are added to the file as #history-N skip links blocks
PProcesses: what runs under the file’s shells, as a tree, with how long each has run; x kills one and what it started
,Run options: arguments, --only, step, stop on error
ctrl+cStop the run, keeping the shells; again kills the shell of a block that won’t stop. Quits when nothing runs
ctrl+]Stop a tty block running in its card
tType in a background tty block’s terminal; ctrl+g gives the keys back, leaving it running
eEdit the block in $VISUAL, $EDITOR or vi; enter runs it
EEdit the whole file the same way, at the block
FFix front matter that doesn’t parse, when mdsh can: quote a value with a : in it
yCopy the block’s code to the clipboard (OSC 52, and the system clipboard locally)
YCopy an http block as a curl command
cCopy text the block’s output offers (marked ⧉1, ⧉2…); again for the next
VSelect lines of History’s output (shift+↑ in the pane too): ↑/↓ j/k extend, g/G ends, o other end, y or enter copies, esc cancels
J/K, alt+↓/↑Move the block, with its output and tape, down or up
uUndo the last move
w, ctrl+sSave; a read-only file opens save as
WSave as another path, relative to the file’s folder
R / MWhen the file changed on disk: reload it / keep yours
pCreate a report: PDF, HTML or markdown
vShow the block’s image or recording full screen; enter goes back
oShow or hide the outline
xShow or hide the selected block’s secret
HShow an http block’s response headers, or its body
bShow or hide the block’s earlier runs, kept by history=N
ZHistory fills the screen; esc gives the document its place back
@Move History to another env the file names (interactive shell): its shell starts interactively, keeping its share; one already run scripted asks first, as it starts again
C / OShow or hide code / output
] / [Next / previous tab
ctrl+tNew tab, on the list of files
ctrl+wClose the tab
qBack to the list of files, or quit
?The keys; ↑/↓ pick one, enter does it, esc closes

In the History pane: tab completes, ↑/↓ or ctrl+p/n recall, ctrl+a/e, ctrl+b/f, alt+b/f, ctrl+w, alt+d, ctrl+u/k, ctrl+y edit, ctrl+l clears, ctrl+o turns recording off (commands run but aren’t added to the file) and on again, alt+enter runs a command and keeps it with the shell’s directory (wd=), esc goes back to the document, ctrl+d closes the pane and turns recording back on. # ```sh starts a block, added without running when a line of ``` ends it; ctrl+c drops it. On the start screen: type to filter, ↑/↓ or tab pick, enter opens, esc goes back, ctrl+c quits. A tty block takes every key while it runs, ctrl+c included.

mdsh-gui

Keys

Keys follow mdsh -i where they don’t clash with the OS. ⌘ on macOS is ctrl on Linux.

KeyDoes
j / kSelect the next / previous block
enterRun the selected block, or the selected heading’s section
aRun from the selected block
sRun the section the selection is in
eEdit the block in the source view
cCopy the block’s code
dDepends On…: edit the block’s depends= as a list
delete, backspaceDelete the selected block
⌘↩ / ⌘⇧↩ / ⌘R / ⌘.Run Current Block / Run Section / Run All / Stop
⌘⌥↩, ⌥-click playRun Current Block in a Side Shell, leaving a command in History running (interactive shell)
⌘⌥KClear All Outputs…
⌘\ / ⌘⇧\Source View / Rendered View
⌘⇧O / ⌘⇧H / ⌘⇧YOutline / History / Console
⌘⇧R / ⌘⇧F / ⌘⇧EHistory: recording off and on / fill the tab / pick its env; each opens the pane if it is closed
⌘⇧MFront Matter form; esc puts the page back
⌥↑ / ⌥↓Move Block Up / Down past the next cell; with ⇧, past the next block
⌘Z / ⌘⇧ZUndo / Redo
⌘N / ⌘T / ⌘⇧N / ⌘ONew File… / New Tab / New Window / Open…
⌘S / ⌘⇧S / ⌘W / ⌘⇧WSave / Save As… / Close Tab / Close Window
⌘⇧] / ⌘⇧[Next / previous tab
⌘,Settings (Preferences on Linux)
⌘QQuit (Linux; macOS has the app menu’s)
escCancel a drag

In the outline ↑/↓ move between entries and ←/→ fold and unfold a section; the window’s tabs take the arrows, enter and delete. The History pane takes the same line keys as mdsh -i’s, alt+enter to run a command and keep it with the shell’s directory (wd=), shift+enter for another line, ctrl+c to stop a command (or copy selected lines), ctrl+z to stop and keep the job, ctrl+d to close; with the interactive shell, the env menu on its bar moves it to another env the file names; # ```sh starts a block as in mdsh -i. Its record button (the dot) turns recording off, so commands run without being added to the file; closing the pane turns it back on. A background block that outlives its run shows Stop in place of its play button. Its separator shows the shell’s working directory, and the button beside its close button has it fill the tab. With Vim keys on, :w saves and :RunBlock and :RunSection run; in the Neovim pane K explains an attribute and zc/zo fold. With Settings › Shell › Interactive shell, the pane is a terminal on the shell, every key goes to it, and the bar under it lists the shell’s jobs.

MenuItems
mdsh (macOS)About mdsh · Settings… · Install / Uninstall Command Line Tool… · Hide · Quit
FileNew File… · New Tab · New Window · Open… · Open Recent · Save · Save As… · Create Report… · Reload · Serve in Browser (with Settings › Shell › Serve notebooks on) · Close Tab · Close Window · Quit (Linux)
EditUndo · Redo · Move Block Up · Move Block Down · Move Block Above Previous Block · Move Block Below Next Block · Depends On… · Front Matter · Cut · Copy · Paste · Select All · Preferences… (Linux)
RunRun Current Block · Run Current Block in a Side Shell · Run Section · Run All · Stop · Clear All Outputs… · Run Options…
ViewSource View · Rendered View · Outline · History · History Pane › Record Commands On or Off, Fill Tab with History, Move History to Env… · Console · Show Code · Show Output · Folding › Collapse All Blocks, Collapse All Sections, Expand All, Copy Folds to Source View, Copy Folds to Rendered View · Zoom In · Zoom Out · Actual Size · Toggle Full Screen · Show Next Tab · Show Previous Tab
HelpCheat Sheet · Changelog · Copy Bug Report
Insert (right-click in the source view)Heading · Bold · Italic · Code · Link · Image · Bulleted List · Numbered List · Task List · Quote · Table · Code Block · sh Block · sh Block, Confirm First · zsh Block · http Request · Textbox · Choice

Settings has six tabs: General, Look, Editing, Shell, Files and About; About links to this cheat sheet and the changelog, which open in read-only tabs. Shell holds the experimental interactive shell and “Start it as a login shell”. Text a program marks for the clipboard (OSC 52, iTerm2’s CopyToClipboard) shows as a copy button in the output, and an out=file block’s output bar says how long its log is and opens it. The Console pane’s Bug Report button, like Help › Copy Bug Report, copies a markdown report of the build, settings, tab, processes and console. Right-clicking a recording offers Copy and Copy as GIF, and the History transcript Copy and Select All. A block with history=N lists its earlier runs under its output, each with copy and delete, and Clear earlier runs; the Report form’s Earlier runs switch prints them. An image from another site or outside the document’s folder has a Load image button, and the document remembers it.