This is a proof-of-concept implementation of literate programming.
The idea is to use documentation as the source for scripts, configuration files or other generating
output via an external helper program.
This implementation was whipped together using shell
scripting and implements
a few basic concepts for generating code from markdown.
We will be using the bourne shell interpreter
The redirect
function is used to modify the stdout target file descriptor.
Initially this will always point to /dev/stdout
(fd1) but can be remapped
to any file or device. Remapping output is persistent.
redirect() {
local file=$1
exec 3>"${file}"
}
The handle_code_block
function implements the two current features
of this POC literate programming parser.
handle_code_block() {
set $*
while [ $# -gt 0 ]; do
case $1 in
The :file modifier will redirect output to the specified target.
:file) shift; redirect "$1";;
Setting this modifier on a code block will disable any output rendering of the
code. This can thus be used to include example code in documentation that
is not to be rendered to file.
:noexport) redirect /dev/null;;
The :stdout modifier will redirect to standard output
:stdout) redirect /dev/stdout;;
The main bulk comes here.
declare -i incode=0
redirect /dev/stdout
sed 's/\\/\\\\/g' | while read LINE; do
case "${incode}${LINE}" in
"0\`\`\`"*) incode=1;handle_code_block "${LINE}";continue;;
"1\`\`\`"*) incode=0;;
esac
if [ ${incode} -ne 0 ]; then
echo ${LINE} >&3
fi
done