This skill enforces literate programming principles when updating .nw files, guiding planning, chunking, and documentation to ensure readable, maintainable
npx playbooks add skill dbosk/claude-skills --skill literate-programming
CRITICAL: This skill MUST be activated BEFORE making any changes to .nw files!
You are an expert in literate programming using the noweb system.
This skill includes detailed references in references/:
| File | Content | Search patterns |
|------|---------|-----------------|
| noweb-commands.md | Tangling, weaving, flags, troubleshooting | notangle, noweave, -R, -L |
| testing-patterns.md | Test organization, placement, dependency testing | test functions, pytest, after implementation |
| overview-patterns.md | Whole-picture overviews, roadmap prose, structural diagrams | overview, diagram, tikz, roadmap |
| git-workflow.md | Version control, .gitignore, pre-commit | git, commit, generated files |
| multi-directory-projects.md | Large project organization, makefiles | src/, doc/, tests/, MODULES |
| project-initialization.md | New project setup, templates, checklist | new project, initialize, pyproject.toml |
| preamble.tex | Standard LaTeX preamble for documentation; verbose biblatex for memoir+didactic margin references | \usepackage, memoir, biblatex, style=verbose |
| build-pythontex-biber.md | Build gotchas: minted v3, the latexmkrc/PythonTeX mylatex fudge (and that latexmkrc is tangled from tex.mk.nw → gitignore it), PythonTeX dirs writing outside the repo, biber-vs-bibtex .bbl routing under -use-make, regenerating didactic.sty from the submodule | latexmkrc, pythontex, bibtexu, didactic.sty, -use-make |
When making changes to a .nw file:
README.mdsummarizes this area, and does this change make it stale?
implement (a file format, quoting, escaping, parsing, locking)?
Use it, or a well-maintained package where that is as well
established and more expressive, flexible and widely used for the
task (check its releases, do not assume); write your own only when
neither exists or the packages are abandoned. Say in the prose why
a package was preferred to the standard library, or own code to
both (what they lack).
.nw files, give maintainers the whole before theparts. If relationships are hard to hold in prose, add a structural
figure. See references/overview-patterns.md.
Key principle: If you find yourself writing code comments to explain logic, that explanation belongs in the documentation chunks instead.
When reviewing, evaluate:
Maintainer-facing .nw files should orient the reader to the system,
then drill into parts, then reconnect changes to the whole.
chunks named with nouns (<<option completions>>), not verb phrases
(<<wire option completions>>)?
explanation should also say why the chosen approach works. Red flags:
prose that begins "We [verb] the [noun]" matching a function name;
prose that describes parameter types visible in the signature;
prose that restates conditionals without explaining why they matter;
prose that says an approach is better without explaining the mechanism,
invariant, or constraint that makes it work.
[[code]] notation in prose? Identifiers inchunk titles escaped with [[...]]? Valid chunk references?
the main parts, how they relate, and where the document will go next?
Is the level appropriate for a maintainer who knows the language but not
this codebase?
hard to track in prose, does the document add a roadmap or diagram?
entry points, or likely edit locations changed, were the overview,
local intro prose, roadmap figures, and any relevant README.md kept in
sync?
assignments, register/install calls, decorator-style mutation) placed
next to the entities they mutate, not the helpers they call? When the
same task is solved in multiple places in the file, do they share a
pattern — or does prose explain why a particular site diverges?
Literate programming (Knuth) has two goals:
Apply variation-theory skill when structuring explanations:
When the literate document is student-facing educational LaTeX — the
students read the woven output — keep pedagogical meta-commentary such as
variation/invariance labels and sequencing rationale out of the visible
narrative. Put that reasoning in \ltnote{...} via the didactic-notes
skill.
\ltnote{...} is also available in an ordinary (maintainer-facing) literate
program, but scope it tightly: it is for reasoning about the exposition, not
the code. A note on why the narrative is ordered as it is — why function A is
explained before function B, why a concept is introduced in this chapter rather
than later, why the whole precedes the parts — is commentary about the writing
and belongs in an \ltnote. A design decision about the code itself (an
architecture choice, why a data structure was picked, the rationale and any
citations behind it) is content: it belongs in the visible body prose. The
test: if removing the note would lose information about the program, it is body
text; if it would only lose information about how the explanation was authored,
it is an \ltnote. See the didactic-notes skill for details.
When the tangled artifact is itself teaching material — a .nw that
tangles to a student-facing tutorial (e.g. a pytorial .md) and weaves to a
maintainer/educator chapter — apply the maintainer-facing rule with the
tutorial in the role of the program. Each layer teaches the layer below it,
so each has its own object of learning: the tangled tutorial teaches the
student the subject; the woven prose teaches the teacher (the
educator/maintainer) the tutorial's design — how the tutorial teaches; an\ltnote teaches the future author how the prose targets the teacher's
learning. Pedagogical rationale about the tutorial (why this step order,
what varies, the critical aspects) is therefore the woven chapter's own
object of learning and belongs in the visible body prose, not in\ltnote — even though it is variation-theory commentary. \ltnote sits
one level above the document's own object of learning: reserve it for how
the woven exposition itself is authored. The test carries over: removing it
loses information about the tutorial → body text; it loses only information
about how the chapter's prose was authored → \ltnote.
If the .nw document generates slides or handouts with live questions, Mentipy
is a suitable tool for embedding those prompts in the LaTeX output; load thementipy skill before writing them.
CRITICAL: Show concrete examples FIRST, then state general principles. Readers cannot discern a pattern without first experiencing variation.
@ followed by space or newline<<chunk name>>= on a line by itself (column 1)<<chunk name>>[[code]] (escapes LaTeX special chars).Never manually escape characters (e.g. \_) inside [[...]] — noweb
handles all escaping automatically. Writing [[\_]] double-escapes.
[[<<chunk name>>]] — the outer[[...]] typesets the reference as code. A bare <<chunk name>> in
prose is not the convention; conversely, when reviewing, do not flag[[<<...>>]] as redundant.
[[...]] works inside \item[...] labels (and other moving arguments),but separate the inner ]] from the outer ] with at least one
character — typically a space. The failure mode is **three brackets in
a row** (]]]), where noweb's ]] terminator and LaTeX's ] argument
terminator collide and produce a `Runaway argument? ! Paragraph ended
before \@item was complete.` error.
GOOD — ]] is followed by a space or by other text:
\item[The [[--restart]] flag] explains the idempotence rule.
\item[ [[shell-basics $]] ] anchors on the nested shell prompt.
BAD — [[...]] butts directly against the closing ]:
\item[The required pattern [[shell-basics $]]] % Runaway argument
The same rule applies to any other LaTeX macro argument that is
delimited with brackets (\caption[...], \section[...] short forms,
etc.). When in doubt, add a trailing space inside the outer brackets.
@<< for literal <<, @@ in column 1 for literal @@ Between Adjacent Code Chunks@ starts a documentation chunk; it is not a code-chunk terminator. A code
chunk already ends the moment any chunk begins — including another named code
chunk. So when one code chunk is immediately followed by another with no prose
between them, no @ is needed: the second chunk closes the first on its
own.
Worse, a stray @ (followed by a blank line) opens an *empty documentation
chunk*, which noweave renders as unwanted vertical space in the woven
PDF.
Rule of thumb: write @ only when documentation prose follows the code. This
is the complement of Writing Guideline 14 (prose-follows ⇒ @; code-follows ⇒
no @).
GOOD — the second chunk ends the first; no @, no empty doc chunk:
<<constants>>=
CONST = 3.14
<<functions>>=
def area_of_circle(radius):
return CONST * radius ** 2
@
BAD — redundant @ opens an empty doc chunk → unwanted space in the PDF:
<<constants>>=
CONST = 3.14
@
<<functions>>=
def area_of_circle(radius):
return CONST * radius ** 2
@
When a tangled script embeds a heredoc (a shell <<EOF ... EOF, an inlinepython3 - <<EOF, a cat > file <<EOF, etc.), **put both the opening<<DELIM and the closing DELIM in the same wrapper chunk, with a single
chunk reference for the body in between.** Define the body in its own chunk
that contains only the payload — never the delimiter.
This matters because noweb chunk boundaries and the heredoc are two
independent layers: noweb blindly concatenates every definition of the body
chunk, and the shell only sees the tangled text. If the closing delimiter is
written inside the body chunk (especially when the body is built from several
concatenated definitions), the heredoc terminates after the first piece and
everything after it tangles as code instead of data — a syntax error far from
its cause.
GOOD — delimiter pair together in the wrapper; body chunk holds only the
payload (and may be split across several definitions safely):
<<write the config>>=
cat > "$file" <<'_EOF'
<<config body>>
_EOF
@
<<config body>>=
first line of payload
@
<<config body>>=
more payload, concatenated by noweb into the same heredoc
@
BAD — the closing delimiter lives in the body chunk, so a second
definition (or any following chunk) escapes the heredoc:
<<write the config>>=
cat > "$file" <<'_EOF'
<<config body>>
@
<<config body>>=
first line of payload
_EOF
@
<<config body>>=
this never reaches the heredoc — it tangles as shell
@
Quote the opening delimiter (<<'_EOF') when the payload must not undergo
shell expansion — for example embedded Python or JSON containing $. A
distinctive delimiter such as _EOF or PYEOF keeps it easy to see the pair
at a glance.
documents should start with an overview of the moving pieces, their
relationships, and the route through the file
Bucket chunks are named with nouns; phase chunks may be imperative.
A bucket chunk holds the same kind of content across many definitions
and is named as a category: <<constants>>, <<functions>>,<<imports>>, <<test functions>>, <<repo methods>>,<<option completions>>. Phase sub-chunks (Guideline 8) are different —
they describe a step in an algorithm and read naturally as imperatives
(<<pick random starting point>>, `<<collect sentences until target
length>>`).
BAD — verb-phrase bucket name:
<<wire option completions>>=
LAYOUT_OPTION.autocompletion = _choice_completer(LAYOUT_CHOICES)
@
GOOD — noun bucket name:
<<option completions>>=
LAYOUT_OPTION.autocompletion = _choice_completer(LAYOUT_CHOICES)
@
function, parameter, attribute) that appears in a chunk title must be
wrapped in [[...]]. This tells noweave to render it as code
(monospace) and prevents LaTeX errors from underscores.
BAD — bare identifier, underscore breaks LaTeX:
<<restrict to top-level when not show_tree>>=
if not show_tree:
...
@
GOOD — identifier escaped with [[...]]:
<<restrict to top-level when not [[show_tree]]>>=
if not show_tree:
...
@
Other examples: <<add graders to [[graders]] list>>,<<initialise [[default_username]]>>.
IMPORTANT: Do not escape underscores or other special characters
inside [[...]]. The brackets already tell noweb to escape
everything. [[__init__.py]] is correct;[[\_\_init\_\_.py]] is wrong and will double-escape.
Prose that merely restates the code in English teaches nothing. Good
prose explains why a design choice was made and *why this approach
works*: what alternative was rejected, what property makes the chosen
approach effective, what would break without it, or what constraint
drives the implementation.
Self-test: If your prose could be mechanically generated from the
function signature, it's "what" not "why." Ask yourself: *What design
decision does this paragraph justify? What alternative did we reject
and why? Why does the chosen approach work here?* If the paragraph
doesn't answer those questions, rewrite it.
BAD — prose restates code in English:
\subsection{Counting $n$-grams}
We count overlapping $n$-grams.
If $n$ is larger than the input, the result is empty.
<<functions>>=
def ngram_counts(text, *, n):
...
@
GOOD — prose explains why this design choice:
\subsection{Counting $n$-grams}
We use overlapping $n$-grams because they capture all positional
contexts---in \enquote{THE}, overlapping bigrams yield TH and HE,
whereas non-overlapping would only yield TH. This matches the
standard definition used in cryptanalysis.
<<functions>>=
def ngram_counts(text, *, n):
...
@
Red flags that prose is "what" not "why":
why X matters
<<functions>>= chunk withprose before it.** Each function (or small group of tightly related
functions) gets its own <<functions>>= chunk preceded by explanatory
prose. Never put multiple unrelated functions in a single chunk.
BAD — four functions crammed into one chunk with minimal prose:
\subsection{Helper Functions}
We provide several utility functions.
<<functions>>=
def normalize_text(text): ...
def letters_only(text): ...
def key_shifts(key): ...
def index_of_coincidence(text): ...
@
GOOD — each function with its own subsection and prose:
\subsection{Text Normalization}
Before analysis, we strip non-alphabetic characters and
convert to lowercase so that frequency counts are meaningful.
<<functions>>=
def normalize_text(text): ...
@
\subsection{Index of Coincidence}
The index of coincidence measures how likely two randomly
chosen letters from a text are identical ...
<<functions>>=
def index_of_coincidence(text): ...
@
more than ~25 lines and contains two or more distinct algorithmic
phases, decompose it into named sub-chunks. Each sub-chunk name
should read like a step in an algorithm description. The prose before
each sub-chunk explains why that phase works the way it does and
what property of the data or algorithm makes the approach succeed.
This is the classic Knuth technique.
BAD — 80-line function with one line of prose:
We generate plaintext by concatenating sentences.
<<functions>>=
deWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.