--- /dev/null
+#!/usr/bin/env bash
+
+# Between stdin and -out, padds level-tree comment sections ("%%%")
+# with LaTeX documentation macrocode environments.
+
+BEGIN='# Strip empty lines and provide begin-end placeholders
+ /^%%%/,$ {
+ $ a % \\end{macrocode}
+ /^\s*$/ d
+ /^%%%/ {
+ i % \\end{macrocode}
+ a % \\begin{macrocode}
+ }
+ }
+'
+
+END='# Remove odd begin-end items
+ 1,/end.*macrocode/ {
+ /end.*macrocode/ d
+ }
+ /begin.*macrocode/ {
+ N
+ /begin.*macrocode.*end.*macrocode/ d
+ }
+'
+
+cat - | \
+ sed -e "$BEGIN" | sed -e "$END"