Skip to content

Instantly share code, notes, and snippets.

@killwing
Created September 22, 2012 10:25
Show Gist options
  • Save killwing/3765772 to your computer and use it in GitHub Desktop.
Save killwing/3765772 to your computer and use it in GitHub Desktop.
[tw2md] convert tiddler of tiddlywiki to strapdownjs
#!/usr/local/bin/node
var fs = require('fs');
Function.prototype.mlstr = function() {
var lines = new String(this);
return lines.substring(lines.indexOf("/*") + 2, lines.lastIndexOf("*/"));
};
String.prototype.dup = function(n) {
var sb = '';
while (n--) {
sb += this;
}
return sb;
};
var strapdownHead = function() {
/*<!DOCTYPE html>
<html>
<title>tw2md</title>
<xmp theme="readable" style="display:none;">
*/
};
var strapdownFoot = function() {
/*</xmp>
<script src="js/strapdown.js"></script>
</html>
*/
};
var convertInline = function(line) {
return line && line.replace(/''(.+)''|\/\/(.+)\/\/|{{{(.+)}}}|(https?:\/\/[\S]*)\s|\[\[(.+)\|(https?:\/\/[\S]*)\]\]|"""(.+)"""/mg,
function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
if ($1) { // bold
return '**' + $1 + '**';
} else if ($2) { // italic
return '*' + $2 + '*';
} else if ($3) { // inline code
return '`' + $3 + '`';
} else if ($4) { // simple link
return '<' + $4 + '>';
} else if ($5 && $6) { // link
return '[' + $5 + '](' + $6 +')';
} else if ($7) { // remove escape
return $7;
}
});
};
var convert = function(text) {
return text && text.replace(/^(!{1,3})\s*(.+)$|^(\*{1,3})\s*(.+)$|^(#{1,3})\s*(.+)$|^(>{1,3})\s*(.+)$|^{{{\n([\s\S]+?)^}}}|^\<code \w+\>\n([\s\S]+?)^\<\/code\>|^(.+)(\n+)/mg,
function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) {
//console.log($0);
if ($1 && $2) { // title
return '#'.dup($1.length+1) + ' ' + convertInline($2);
} else if ($3 && $4) { // unorder list
return ' '.dup($3.length-1) + '* ' + convertInline($4);
} else if ($5 && $6) { // order list
return ' '.dup($5.length-1) + '1. ' + convertInline($6);
} else if ($7 && $8) { // quote
return '>'.dup($7.length) + ' ' + convertInline($8);
} else if ($9) { // code block
return '```\n' + $9 + '```';
} else if ($10) { // code block
return '```\n' + $10 + '```';
} else if ($11 && $12) { // normal line
return convertInline($0);
}
});
};
var read = function(file, completer) {
fs.readFile(file, 'utf-8', function(err, data) {
if (err) {
throw err;
}
var newdata = convert(data);
//console.log(newdata);
fs.writeFile(file+'.html', strapdownHead.mlstr() + newdata + strapdownFoot.mlstr(), function(err) {
if (err) {
throw err;
}
});
});
};
// main
(function() {
if (process.argv.length < 3) {
console.log('Pls indicate your input tiddler file');
return;
}
read(process.argv[2]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment