Skip to content

Instantly share code, notes, and snippets.

@jtacoma
Created December 4, 2011 03:31
Show Gist options
  • Save jtacoma/1429058 to your computer and use it in GitHub Desktop.
Save jtacoma/1429058 to your computer and use it in GitHub Desktop.
Literate programming with HTML source files using Node and jQuery.
var $ = require('jquery');
function chunkify(rawHtml, chunks) {
var woven = $(rawHtml).find("code[title!='']");
for (var i = 0; i < woven.length; ++i) {
var element = $(woven[i]);
var content = element.text();
var name = element.attr("title");
if (chunks[name])
chunks[name] = chunks[name].concat(content);
else
chunks[name] = content;
}
}
function tangle(content, chunks) {
var noMore = null;
var todo = true;
while (todo)
for (var key in chunks) {
if (key == noMore) {
todo = false;
break;
}
regexp = new RegExp("<<" + key + ">>", "g");
if (regexp.test(content)) {
content = content.replace(regexp, chunks[key]);
noMore = key;
} else if (noMore == null) {
noMore = key;
}
}
return content;
}
function main() {
var fs = require('fs');
var path = process.argv[2];
var content = fs.readFileSync(path, 'utf-8');
var chunks = { '*': '' };
chunkify(content, chunks);
console.log(tangle(chunks['*'], chunks));
}
main();
var version = "0.1";
function foo(arg) {
return arg;
}
function bar(arg) {
var result;
result = foo(arg);
return result;
}
<html><body><div id="content">
...some commentary...
<pre><code title="Functions">
function foo(arg) {
return arg;
}
</code></pre>
...further commentary...
<pre><code title="Functions">
function bar(arg) {
var result;
&lt;&lt;Some hard work&gt;&gt;
return result;
}
</code></pre>
...focusing on the hard part for extra clarity...
<pre><code title="Some hard work">
result = foo(arg);
</code></pre>
...summary thus far...
<pre><code title="Definitions">
var version = "0.1";
</code></pre>
...and top-level flow, almost an after-thought:
<pre><code title="*">
&lt;&lt;Definitions&gt;&gt;
&lt;&lt;Functions&gt;&gt;
</code></pre>
</div></body></html>
node bootstrap.sh sample.html > result.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment