GWEB is a literate programming
system for the Go programming language, modeled closely on Donald Knuth and Silvio Levy's
CWEB. You write a single .gw source file that interleaves TeX
documentation with Go code, and two tools turn it into either a program or a
typeset document — exactly as CWEB does for C, with C replaced by Go:
| CWEB | GWEB | purpose |
|---|---|---|
ctangle |
gtangle |
extract compilable source (.go) for the machine |
cweave |
gweave |
produce a typeset document (.tex → PDF) for people |
gtanglestrips the documentation, reassembles the named code sections in the order the Go compiler needs, and writesgofmt-formatted.gofiles.gweaveproduces a TeX file in which reserved words are bold, identifiers are italic, strings are typewriter, named sections are linked by number, and a cross-referenced index and list of refinements are generated automatically. Declaredtypenames are set bold, and a constant whose name has no lowercase letter (TRAP,MAX_N) typewriter, as CWEB sets such names; other constants,iotaor not, stay italic. Mark any name typewriter with@d(e.g. another package's@d http.StatusOK), and override any of it with@f/@s.
GWEB assumes you already know Go and are comfortable with TeX — in
particular plain TeX, since gwebmac.tex and this repository's macros are
plain TeX, not LaTeX. Beyond that:
-
A TeX distribution (e.g. TeX Live or MacTeX) must be installed, providing the
tex,pdftex, andluatexengines the woven output is typeset with. -
For Korean output (
\input kotexgweb; see Usage), the Noto Serif/Sans CJK KR fonts must be installed locally —hangulfont.texselects them by name. Download them from the noto-cjk releases — these three archives together hold every facehangulfont.texnames, under the SIL Open Font License:08_NotoSerifCJKkr.zip— Noto Serif CJK KR07_NotoSansCJKkr.zip— Noto Sans CJK KR12_NotoSansMonoCJKkr.zip— Noto Sans Mono CJK KR
Take these region-specific
…CJKkrpackages, not the smallerNotoSerifKR/NotoSansKRones, whose fonts are named "Noto Serif KR" and are not found. Unzip them and install the.otffiles the usual way for your system — e.g. copy them into~/Library/Fontson macOS, or into~/.local/share/fontson Linux and runfc-cache -f— so thatluatexcan find them by name.
make build # builds bin/gtangle and bin/gweave
make test # runs the test suiteAs in CWEB, only the Go needed to build gtangle is committed; gweave and the
weave engine are tangled from their .gw sources on the fly. make build does
this for you: it builds gtangle from the committed sources, runs it to generate
the rest, then builds gweave. (make generate performs just the tangling step.)
So build through make, not a bare go build ./..., on a fresh checkout.
Producing a PDF additionally requires a TeX engine (e.g. pdftex, from TeX
Live or MacTeX).
gtangle installs the Go way (its sources are committed):
go install github.com/sjnam/gweb/cmd/gtangle@latestgweave is generated rather than committed, so install both from a checkout
with make install (or make install-tools to put just the binaries in your
GOBIN). Point TEXINPUTS at a copy of gwebmac.tex so
the TeX engine can find it.
For a full install — the commands plus gwebmac.tex (placed in your TeX tree
so pdftex foo.tex just works) plus the man page — use the install script:
./install.sh # into ~ (TEXMFHOME) and /usr/local (may need sudo)
./install.sh --prefix="$HOME/.local" # a writable prefix, no sudo
sudo ./install.sh # system-wide
./install.sh --uninstall # remove everything it installedmake install / make uninstall call the script (pass options with
ARGS=...); run ./install.sh --help for all options (--bindir, --mandir,
--texmf). Then man gtangle / man gweave describe the commands.
gtangle foo.gw # -> foo.go (plus any @(file@>= outputs)
gweave foo.gw # -> foo.tex
pdftex foo.tex # -> foo.pdf (gwebmac.tex must be on TEXINPUTS)The .gw extension may be omitted, as CWEB's .w may — gtangle foo reads
foo.gw (and a bare change-file name gets .ch). GWEB webs used to end in .w
too, but that extension is CWEB's: GNU make has built-in rules that hand any
.w file to ctangle and cweave, and editors and GitHub read it as CWEB. A web
still named foo.w keeps working — a bare foo falls back to it when there is no
foo.gw — and a name given with its extension is used as it is. Each command
prints a brief cweb-style progress line, one *N per starred (chapter) section.
For a hyperlinked PDF you can also go through DVI, exactly as CWEB does — request
the \special{pdf:…} back end with \let\pdf+, then convert with dvipdfmx:
tex "\let\pdf+ \input foo.tex" # -> foo.dvi (with pdf: specials)
dvipdfmx foo.dvi # -> foo.pdf (links + bookmarks)Both commands accept -o <dir> to choose an output directory, and an optional
change file as a second argument — gtangle foo.gw foo.ch — which patches the
master source without editing it (CWEB's .ch mechanism; see
format.md). For example,
gtangle examples/wc.gw examples/wc.ch builds a CSV variant of the word counter. When
gweave runs with a change file it marks each altered or added section with a *
after its number (on the heading, in the index, and in cross-reference notes) and
lists the changed sections just before the index, exactly as CWEB does. gwebmac.tex
lives at the repository root; point TEXINPUTS there, or copy the file
next to your document.
The tangled Go always carries //line directives, so the Go compiler, go vet,
and panic traces report errors at .gw positions instead of .go ones — the
Go counterpart of CWEB's #line, which ctangle likewise emits unconditionally:
gtangle foo.gw && go build . # an error reads foo.gw:42: ...GWEB tangles its own sources the same way, so editing a .gw reshuffles the line
numbers in the bootstrap Go it commits — the price of keeping the generated code
honest about its literate origin.
For a tour of the bundled examples, the full .gw file-format reference, and
non-English (e.g. Korean) documentation, see the manual — gwebman.tex
(make manual). A Korean translation, gwebman-ko.tex, is built with
make manual-ko (it needs luatex and the Korean fonts listed under
Prerequisites).
The examples/ directory here is deliberately small — just enough to exercise
the tools. For GWEB used in earnest, see the companion repository:
sjnam/gweb-examples — some forty
literate Go programs, each in a directory of its own with its .w, a README, and
any change files, MetaPost files, or data it needs; one Makefile builds them all
into a single Go module. Most are translations of Knuth's own CWEB programs. They
range over backtracking and exhaustive search (back-20q.w, back-pi-day.w,
back-dissect.w, sliding.w), graph algorithms (tarjan-strong.w,
hopcroft-karp.w, matula.w, grayspan.w), combinatorial generation
(koda-ruskey.w, li-ruskey.w, spiders.w), and serious counting
(ulam-gibbs.w, polynum.w, prime-sieve.w). Beside them stand expositions of
algorithms worth knowing — zip trees (ziptree.w), the FFT and number-theoretic
transforms (ntt.w), Li Chao trees (pairsums.w), Floyd's random sampling
(perm.w) — and the odd literary detour: perec.w rebuilds Perec's Life A
User's Manual from its two constraints. All are written in Korean via
\input kotexgweb, and most carry MetaPost figures drawn during typesetting by
luamplib, so the repository doubles as a demonstration of what a finished
GWEB document can look like — and of the Korean and LuaTeX support described
above.
Four larger projects carry whole Knuth programs into GWEB, each a Korean translation that turns his Pascal (or C) into Go section by section, keeping his sections, names, and structure so it reads side by side with the original:
- sjnam/tex-the-program —
TeX: The Program (
tex.web, version 3.141592653) as a singletex.w. It yields both a book of some 860 pages and a workingtexthat passes Knuth's TRIP test. - sjnam/metafont-the-program
— its companion, METAFONT: The Program (
mf.web, version 2.71828182) asmf.w, a book of some 900 pages with 26 MetaPost figures the original lacks, and a workingmfthat writes the same TFM and GF files as METAFONT and passes the TRAP test. - sjnam/go-mmix — Knuth's MMIXware:
the MMIX specification (
mmixdoc.w), the arithmetic and I/O libraries, the assemblermmixal, the simulator,mmotype, and the pipelined meta-simulatormmmix, every section translated. Each program was checked against Knuth's C original to give byte-for-byte the same output on the same input. - sjnam/go-sgb — the Stanford GraphBase,
its kernel (
gbflip,gbio,gbgraph,gbsort) and graph generators, one web per package. Thesham.gwexample here builds on it.
Each .gw source sits next to the Go it generates. Only the Go that bootstraps
gtangle is committed (◇ below); the rest (✦) is tangled by make.
gweb.gw the master web: @i-includes the three below (woven, not tangled)
cmd/
├── gtangle/ gtangle.gw -> gtangle: front end + the tangle engine ◇
└── gweave/ gweave.gw -> gweave: front end + the weave engine (lexer, ✦
pretty-printer, cross-references)
common/ common.gw -> the shared parser (CWEB's common.w) ◇
gwebmac.tex TeX macros for woven output (CWEB's cwebmac.tex)
kotexgweb.tex Korean (luatexko) localization
hangulfont.tex the Hangul typeface choices (\input by kotexgweb.tex)
gweb.1 the man page for both commands (CWEB's cweb.1)
format.md the .gw file-format reference
gwebman.tex the GWEB manual
gwebman-ko.tex the manual in Korean (make manual-ko; luatex)
examples/ worked examples
editors/
└── vscode/ VS Code language support for .gw files
install.sh installer for the commands, gwebmac.tex, and the man page
For editor support and how GWEB's self-hosting (make tangle, make bootstrap, make selfdoc) works, see the manual as well.
- Lexing for free. Tangle relies on
gofmt(go/format) to canonicalize the assembled program, so the emitted Go is always tidily formatted as long as the web assembles into valid Go. - Pretty-printing.
gweavehighlights tokens (bold keywords, italic identifiers, typewriter strings, real math symbols for≤ ≥ ≠ ←, …) and mirrors the source's own spacing rather than re-deriving layout from a full Go grammar the way CWEB does for C. Because gofmt-formatted Go already encodes the grammar in its spacing, mirroring it reproduces gofmt exactly — including the tricky cases (*Tvsa * b,[]Tvsa[i], precedence spacing likea*b + c) — without any parsing. Long code lines wrap at the inter-token spaces, with continuation lines indented one step deeper. Write the code in your sections in gofmt style for the best-looking output. - Definition detection in the index is heuristic (the names a
func/var/const/typedeclares — singly, as a list likevar a, b int, or as entries of a parenthesized group — every name left of a:=, the fields of astructother than embedded ones, and method names), not a full type check. It looks at one code part at a time, so fields spliced into astructfrom another section need an@!. A defined type's index entry, like its uses, is set bold, as CWEB sets atypedef. Predeclared types such asintandstringare left out of the index, as CWEB leaves outint. - Diagnostics. Both tools report, with
file:linelocations, unterminated control codes, references to undefined sections, ambiguous...abbreviations, and named sections defined but never used. These are warnings;gtanglestill stops if it must actually expand an undefined reference. An origin map kept in step through@iincludes and change-file edits makes every location point back to the file (and line) you actually wrote. - Page layout follows cweave.
gwebmac.texgives the woven document the same furniture CWEB produces: run-in bold section headings (with a page break before each major starred section),§sec JOBNAME … GROUPTITLE pagerunning heads, a title-less index that sits under your own@* Index.section, a Names of the Sections list, and a contents page (centered title,Section/Pagecolumns, dotted leaders). The index is set in two columns. As in CWEB, the contents page is produced at the end in a single TeX pass; move it to the front when binding if you prefer. The font set mirrorscwebmac.tex(medium-caps\mc, thecmtex10string font, …), and a fewcwebmacprose helpers are available in commentary:\CEE/,\GO/,\UNIX/,\TEX/, and\\{id}for an italic identifier (though the GWEB idiom for inline code is|id|). - Hyperlinks and bookmarks. Every section number shown as a reference, in the
index, in a cross-reference note, or on the contents page is a blue link to that
section; clicking it jumps there (for the underlined index entries, to where the
identifier is defined). The starred sections also become a PDF outline (bookmark
tree), nested by their
@*,@*1,@*2depths. Two back ends produce these: the engine's PDF primitives in PDF mode —pdftexhas them directly, and underluatexgwebmac.texshims them onto\pdfextension(as CWEB does), so a web woven forluatex, e.g. forluamplibfigures or Korean, gets the links and outline too; and the DVI route, which emits\special{pdf:…}commands fordvipdfmxwhen you ask for them with\let\pdf+(the same convention as CWEB). With a plain DVI engine and no\let\pdf+, they are simply omitted.
GWEB is released into the public domain under the Unlicense: anyone may copy, modify, publish, use, compile, sell, or distribute it, for any purpose, without asking.