-
+
diff --git a/tools/doc/README.md b/tools/doc/README.md
new file mode 100644
index 00000000000..67ff2e1df51
--- /dev/null
+++ b/tools/doc/README.md
@@ -0,0 +1,96 @@
+Here's how the node docs work.
+
+1:1 relationship from `lib/.js` to `doc/api/.markdown`
+
+Each type of heading has a description block.
+
+
+ ## module
+
+ Stability: 3 - Stable
+
+ description and examples.
+
+ ### module.property
+
+ * Type
+
+ description of the property.
+
+ ### module.someFunction(x, y, [z=100])
+
+ * `x` {String} the description of the string
+ * `y` {Boolean} Should I stay or should I go?
+ * `z` {Number} How many zebras to bring.
+
+ A description of the function.
+
+ ### Event: 'blerg'
+
+ * Argument: SomeClass object.
+
+ Modules don't usually raise events on themselves. `cluster` is the
+ only exception.
+
+ ## Class: SomeClass
+
+ description of the class.
+
+ ### Class Method: SomeClass.classMethod(anArg)
+
+ * `anArg` {Object} Just an argument
+ * `field` {String} anArg can have this field.
+ * `field2` {Boolean} Another field. Default: `false`.
+ * Return: {Boolean} `true` if it worked.
+
+ Description of the method for humans.
+
+ ### someClass.nextSibling()
+
+ * Return: {SomeClass object | null} The next someClass in line.
+
+ ### someClass.someProperty
+
+ * String
+
+ The indication of what someProperty is.
+
+ ### Event: 'grelb'
+
+ * `isBlerg` {Boolean}
+
+ This event is emitted on instances of SomeClass, not on the module itself.
+
+
+* Modules have (description, Properties, Functions, Classes, Examples)
+* Properties have (type, description)
+* Functions have (list of arguments, description)
+* Classes have (description, Properties, Methods, Events)
+* Events have (list of arguments, description)
+* Methods have (list of arguments, description)
+* Properties have (type, description)
+
+## Stability ratings: 0-5
+
+These can show up below any section heading, and apply to that section.
+
+0 - Deprecated. This feature is known to be problematic, and changes are
+planned. Do not rely on it. Use of the feature may cause warnings. Backwards
+compatibility should not be expected.
+
+1 - Experimental. This feature was introduced recently, and may change
+or be removed in future versions. Please try it out and provide feedback.
+If it addresses a use-case that is important to you, tell the node core team.
+
+2 - Unstable. The API is in the process of settling, but has not yet had
+sufficient real-world testing to be considered stable. Backwards-compatibility
+will be maintained if reasonable.
+
+3 - Stable. The API has proven satisfactory, but cleanup in the underlying
+code may cause minor changes. Backwards-compatibility is guaranteed.
+
+4 - API Frozen. This API has been tested extensively in production and is
+unlikely to ever have to change.
+
+5 - Locked. Unless serious bugs are found, this code will not ever
+change. Please do not suggest changes in this area, they will be refused.
diff --git a/tools/doc/generate.js b/tools/doc/generate.js
new file mode 100755
index 00000000000..f866c0120bb
--- /dev/null
+++ b/tools/doc/generate.js
@@ -0,0 +1,99 @@
+#!node
+
+var marked = require('marked');
+var fs = require('fs');
+var path = require('path');
+
+// parse the args.
+// Don't use nopt or whatever for this. It's simple enough.
+
+var args = process.argv.slice(2);
+var format = 'json';
+var template = null;
+var inputFile = null;
+
+args.forEach(function (arg) {
+ if (!arg.match(/^\-\-/)) {
+ inputFile = arg;
+ } else if (arg.match(/^\-\-format=/)) {
+ format = arg.replace(/^\-\-format=/, '');
+ } else if (arg.match(/^\-\-template=/)) {
+ template = arg.replace(/^\-\-template=/, '');
+ }
+})
+
+
+if (!inputFile) {
+ throw new Error('No input file specified');
+}
+
+
+console.error('Input file = %s', inputFile);
+fs.readFile(inputFile, 'utf8', function(er, input) {
+ if (er) throw er;
+ // process the input for @include lines
+ processIncludes(input, next);
+});
+
+
+var includeExpr = /^@include\s+([A-Za-z0-9-_]+)(?:\.)?([a-zA-Z]*)$/gmi;
+var includeData = {};
+function processIncludes(input, cb) {
+ var includes = input.match(includeExpr);
+ if (includes === null) return cb(null, input);
+ var errState = null;
+ console.error(includes);
+ var incCount = includes.length;
+ if (incCount === 0) cb(null, input);
+ includes.forEach(function(include) {
+ var fname = include.replace(/^@include\s+/, '');
+ if (!fname.match(/\.markdown$/)) fname += '.markdown';
+
+ if (includeData.hasOwnProperty(fname)) {
+ input = input.split(include).join(includeData[fname]);
+ incCount--;
+ if (incCount === 0) {
+ return cb(null, input);
+ }
+ }
+
+ var fullFname = path.resolve(path.dirname(inputFile), fname);
+ fs.readFile(fullFname, 'utf8', function(er, inc) {
+ if (errState) return;
+ if (er) return cb(errState = er);
+ processIncludes(inc, function(er, inc) {
+ if (errState) return;
+ if (er) return cb(errState = er);
+ incCount--;
+ includeData[fname] = inc;
+ input = input.split(include).join(includeData[fname]);
+ if (incCount === 0) {
+ return cb(null, input);
+ }
+ });
+ });
+ });
+}
+
+
+function next(er, input) {
+ if (er) throw er;
+ switch (format) {
+ case 'json':
+ require('./json.js')(input, inputFile, function(er, obj) {
+ console.log(JSON.stringify(obj, null, 2));
+ if (er) throw er;
+ });
+ break;
+
+ case 'html':
+ require('./html.js')(input, inputFile, template, function(er, html) {
+ if (er) throw er;
+ console.log(html);
+ });
+ break;
+
+ default:
+ throw new Error('Invalid format: ' + format);
+ }
+}
diff --git a/tools/doc/html.js b/tools/doc/html.js
new file mode 100644
index 00000000000..0ffedb1ecc9
--- /dev/null
+++ b/tools/doc/html.js
@@ -0,0 +1,154 @@
+var fs = require('fs');
+var marked = require('marked');
+var path = require('path');
+
+module.exports = toHTML;
+
+function toHTML(input, filename, template, cb) {
+ var lexed = marked.lexer(input);
+ fs.readFile(template, 'utf8', function(er, template) {
+ if (er) return cb(er);
+ render(lexed, filename, template, cb);
+ });
+}
+
+function render(lexed, filename, template, cb) {
+ // get the section
+ var section = getSection(lexed);
+
+ filename = path.basename(filename, '.markdown');
+
+ lexed = parseLists(lexed);
+
+ // generate the table of contents.
+ // this mutates the lexed contents in-place.
+ buildToc(lexed, filename, function(er, toc) {
+ if (er) return cb(er);
+
+ template = template.replace(/__FILENAME__/g, filename);
+ template = template.replace(/__SECTION__/g, section);
+ template = template.replace(/__VERSION__/g, process.version);
+ template = template.replace(/__TOC__/g, toc);
+
+ // content has to be the last thing we do with
+ // the lexed tokens, because it's destructive.
+ content = marked.parser(lexed);
+ template = template.replace(/__CONTENT__/g, content);
+
+ cb(null, template);
+ });
+}
+
+
+// just update the list item text in-place.
+// lists that come right after a heading are what we're after.
+function parseLists(input) {
+ var state = null;
+ var depth = 0;
+ var output = [];
+ output.links = input.links;
+ input.forEach(function(tok) {
+ if (state === null) {
+ if (tok.type === 'heading') {
+ state = 'AFTERHEADING';
+ }
+ output.push(tok);
+ return;
+ }
+ if (state === 'AFTERHEADING') {
+ if (tok.type === 'code') return;
+ if (tok.type === 'list_start') {
+ state = 'LIST';
+ if (depth === 0) {
+ output.push({ type:'html', text: '
' });
+ }
+ output.push(tok);
+ return;
+ }
+ if (tok.text) {
+ tok.text = parseListItem(tok.text);
+ }
+ }
+ output.push(tok);
+ });
+
+ return output;
+}
+
+
+function parseListItem(text) {
+ text = text.replace(/\{([^\}]+)\}/, '$1');
+ //XXX maybe put more stuff here?
+ return text;
+}
+
+
+// section is just the first heading
+function getSection(lexed) {
+ var section = '';
+ for (var i = 0, l = lexed.length; i < l; i++) {
+ var tok = lexed[i];
+ if (tok.type === 'heading') return tok.text;
+ }
+ return '';
+}
+
+
+function buildToc(lexed, filename, cb) {
+ var indent = 0;
+ var toc = [];
+ var depth = 0;
+ lexed.forEach(function(tok) {
+ if (tok.type !== 'heading') return;
+ if (tok.depth - depth > 1) {
+ return cb(new Error('Inappropriate heading level\n' +
+ JSON.stringify(tok)));
+ }
+
+ depth = tok.depth;
+ var id = getId(filename + '_' + tok.text.trim());
+ toc.push(new Array((depth - 1) * 2 + 1).join(' ') +
+ '* ' +
+ tok.text + '');
+ tok.text += '#';
+ });
+
+ toc = marked.parse(toc.join('\n'));
+ cb(null, toc);
+}
+
+var idCounters = {};
+function getId(text) {
+ text = text.toLowerCase();
+ text = text.replace(/[^a-z0-9]+/g, '_');
+ text = text.replace(/^_+|_+$/, '');
+ text = text.replace(/^([^a-z])/, '_$1');
+ if (idCounters.hasOwnProperty(text)) {
+ text += '_' + (++idCounters[text]);
+ } else {
+ idCounters[text] = 0;
+ }
+ return text;
+}
+
diff --git a/tools/doc/json.js b/tools/doc/json.js
new file mode 100644
index 00000000000..4138fbad308
--- /dev/null
+++ b/tools/doc/json.js
@@ -0,0 +1,536 @@
+module.exports = doJSON;
+
+// Take the lexed input, and return a JSON-encoded object
+// A module looks like this: https://gist.github.com/1777387
+
+var marked = require('marked');
+
+function doJSON(input, filename, cb) {
+ var root = {source: filename};
+ var stack = [root];
+ var depth = 0;
+ var current = root;
+ var state = null;
+ var lexed = marked.lexer(input);
+ lexed.forEach(function (tok) {
+ var type = tok.type;
+ var text = tok.text;
+
+ //
+ // This is for cases where the markdown semantic structure is lacking.
+ if (type === 'paragraph' || type === 'html') {
+ var metaExpr = /\n*/g;
+ text = text.replace(metaExpr, function(_0, k, v) {
+ current[k.trim()] = v.trim();
+ return '';
+ });
+ text = text.trim();
+ if (!text) return;
+ }
+
+ if (type === 'heading' &&
+ !text.trim().match(/^example/i)) {
+ if (tok.depth - depth > 1) {
+ return cb(new Error('Inappropriate heading level\n'+
+ JSON.stringify(tok)));
+ }
+
+ // Sometimes we have two headings with a single
+ // blob of description. Treat as a clone.
+ if (current &&
+ state === 'AFTERHEADING' &&
+ depth === tok.depth) {
+ var clone = current;
+ current = newSection(tok);
+ current.clone = clone;
+ // don't keep it around on the stack.
+ stack.pop();
+ } else {
+ // if the level is greater than the current depth,
+ // then it's a child, so we should just leave the stack
+ // as it is.
+ // However, if it's a sibling or higher, then it implies
+ // the closure of the other sections that came before.
+ // root is always considered the level=0 section,
+ // and the lowest heading is 1, so this should always
+ // result in having a valid parent node.
+ var d = tok.depth;
+ while (d <= depth) {
+ finishSection(stack.pop(), stack[stack.length - 1]);
+ d++;
+ }
+ current = newSection(tok);
+ }
+
+ depth = tok.depth;
+ stack.push(current);
+ state = 'AFTERHEADING';
+ return;
+ } // heading
+
+ // Immediately after a heading, we can expect the following
+ //
+ // { type: 'code', text: 'Stability: ...' },
+ //
+ // a list: starting with list_start, ending with list_end,
+ // maybe containing other nested lists in each item.
+ //
+ // If one of these isnt' found, then anything that comes between
+ // here and the next heading should be parsed as the desc.
+ var stability
+ if (state === 'AFTERHEADING') {
+ if (type === 'code' &&
+ (stability = text.match(/^Stability: ([0-5])(?:\s*-\s*)?(.*)$/))) {
+ current.stability = parseInt(stability[1], 10);
+ current.stabilityText = stability[2].trim();
+ return;
+ } else if (type === 'list_start' && !tok.ordered) {
+ state = 'AFTERHEADING_LIST';
+ current.list = current.list || [];
+ current.list.push(tok);
+ current.list.level = 1;
+ } else {
+ current.desc = current.desc || [];
+ if (!Array.isArray(current.desc)) {
+ current.shortDesc = current.desc;
+ current.desc = [];
+ }
+ current.desc.push(tok);
+ state = 'DESC';
+ }
+ return;
+ }
+
+ if (state === 'AFTERHEADING_LIST') {
+ current.list.push(tok);
+ if (type === 'list_start') {
+ current.list.level++;
+ } else if (type === 'list_end') {
+ current.list.level--;
+ }
+ if (current.list.level === 0) {
+ state = 'AFTERHEADING';
+ processList(current);
+ }
+ return;
+ }
+
+ current.desc = current.desc || [];
+ current.desc.push(tok);
+
+ });
+
+ // finish any sections left open
+ while (root !== (current = stack.pop())) {
+ finishSection(current, stack[stack.length - 1]);
+ }
+
+ return cb(null, root)
+}
+
+
+// go from something like this:
+// [ { type: 'list_item_start' },
+// { type: 'text',
+// text: '`settings` Object, Optional' },
+// { type: 'list_start', ordered: false },
+// { type: 'list_item_start' },
+// { type: 'text',
+// text: 'exec: String, file path to worker file. Default: `__filename`' },
+// { type: 'list_item_end' },
+// { type: 'list_item_start' },
+// { type: 'text',
+// text: 'args: Array, string arguments passed to worker.' },
+// { type: 'text',
+// text: 'Default: `process.argv.slice(2)`' },
+// { type: 'list_item_end' },
+// { type: 'list_item_start' },
+// { type: 'text',
+// text: 'silent: Boolean, whether or not to send output to parent\'s stdio.' },
+// { type: 'text', text: 'Default: `false`' },
+// { type: 'space' },
+// { type: 'list_item_end' },
+// { type: 'list_end' },
+// { type: 'list_item_end' },
+// { type: 'list_end' } ]
+// to something like:
+// [ { name: 'settings',
+// type: 'object',
+// optional: true,
+// settings:
+// [ { name: 'exec',
+// type: 'string',
+// desc: 'file path to worker file',
+// default: '__filename' },
+// { name: 'args',
+// type: 'array',
+// default: 'process.argv.slice(2)',
+// desc: 'string arguments passed to worker.' },
+// { name: 'silent',
+// type: 'boolean',
+// desc: 'whether or not to send output to parent\'s stdio.',
+// default: 'false' } ] } ]
+
+function processList(section) {
+ var list = section.list;
+ var values = [];
+ var current;
+ var stack = [];
+
+ // for now, *just* build the heirarchical list
+ list.forEach(function(tok) {
+ var type = tok.type;
+ if (type === 'space') return;
+ if (type === 'list_item_start') {
+ if (!current) {
+ var n = {};
+ values.push(n);
+ current = n;
+ } else {
+ current.options = current.options || [];
+ stack.push(current);
+ var n = {};
+ current.options.push(n);
+ current = n;
+ }
+ return;
+ } else if (type === 'list_item_end') {
+ if (!current) {
+ throw new Error('invalid list - end without current item\n' +
+ JSON.stringify(tok) + '\n' +
+ JSON.stringify(list));
+ }
+ current = stack.pop();
+ } else if (type === 'text') {
+ if (!current) {
+ throw new Error('invalid list - text without current item\n' +
+ JSON.stringify(tok) + '\n' +
+ JSON.stringify(list));
+ }
+ current.textRaw = current.textRaw || '';
+ current.textRaw += tok.text + ' ';
+ }
+ });
+
+ // shove the name in there for properties, since they are always
+ // just going to be the value etc.
+ if (section.type === 'property' && values[0]) {
+ values[0].textRaw = '`' + section.name + '` ' + values[0].textRaw;
+ }
+
+ // now pull the actual values out of the text bits.
+ values.forEach(parseListItem);
+
+ // Now figure out what this list actually means.
+ // depending on the section type, the list could be different things.
+
+ switch (section.type) {
+ case 'ctor':
+ case 'classMethod':
+ case 'method':
+ // each item is an argument, unless the name is 'return',
+ // in which case it's the return value.
+ section.signatures = section.signatures || [];
+ var sig = {}
+ section.signatures.push(sig);
+ sig.params = values.filter(function(v) {
+ if (v.name === 'return') {
+ sig.return = v;
+ return false;
+ }
+ return true;
+ });
+ parseSignature(section.textRaw, sig);
+ break;
+
+ case 'property':
+ // there should be only one item, which is the value.
+ // copy the data up to the section.
+ var value = values[0] || {};
+ delete value.name;
+ section.typeof = value.type;
+ delete value.type;
+ Object.keys(value).forEach(function(k) {
+ section[k] = value[k];
+ });
+ break;
+
+ case 'event':
+ // event: each item is an argument.
+ section.params = values;
+ break;
+ }
+
+ // section.listParsed = values;
+ delete section.list;
+}
+
+
+// textRaw = "someobject.someMethod(a, [b=100], [c])"
+function parseSignature(text, sig) {
+ var params = text.match(paramExpr);
+ if (!params) return;
+ params = params[1];
+ // the ] is irrelevant. [ indicates optionalness.
+ params = params.replace(/\]/g, '');
+ params = params.split(/,/)
+ params.forEach(function(p, i, _) {
+ p = p.trim();
+ if (!p) return;
+ var param = sig.params[i];
+ var optional = false;
+ var def;
+ // [foo] -> optional
+ if (p.charAt(0) === '[') {
+ optional = true;
+ p = p.substr(1);
+ }
+ var eq = p.indexOf('=');
+ if (eq !== -1) {
+ def = p.substr(eq + 1);
+ p = p.substr(0, eq);
+ }
+ if (!param) {
+ param = sig.params[i] = { name: p };
+ }
+ // at this point, the name should match.
+ if (p !== param.name) {
+ console.error('Warning: invalid param "%s"', p);
+ console.error(' > ' + JSON.stringify(param));
+ console.error(' > ' + text);
+ }
+ if (optional) param.optional = true;
+ if (def !== undefined) param.default = def;
+ });
+}
+
+
+function parseListItem(item) {
+ if (item.options) item.options.forEach(parseListItem);
+ if (!item.textRaw) return;
+
+ // the goal here is to find the name, type, default, and optional.
+ // anything left over is 'desc'
+ var text = item.textRaw.trim();
+ // text = text.replace(/^(Argument|Param)s?\s*:?\s*/i, '');
+
+ text = text.replace(/^, /, '').trim();
+ var retExpr = /^returns?\s*:?\s*/i;
+ var ret = text.match(retExpr);
+ if (ret) {
+ item.name = 'return';
+ text = text.replace(retExpr, '');
+ } else {
+ var nameExpr = /^['`"]?([^'`": \{]+)['`"]?\s*:?\s*/;
+ var name = text.match(nameExpr);
+ if (name) {
+ item.name = name[1];
+ text = text.replace(nameExpr, '');
+ }
+ }
+
+ text = text.trim();
+ var defaultExpr = /\(default\s*[:=]?\s*['"`]?([^, '"`]*)['"`]?\)/i;
+ var def = text.match(defaultExpr);
+ if (def) {
+ item.default = def[1];
+ text = text.replace(defaultExpr, '');
+ }
+
+ text = text.trim();
+ var typeExpr = /^\{([^\}]+)\}/;
+ var type = text.match(typeExpr);
+ if (type) {
+ item.type = type[1];
+ text = text.replace(typeExpr, '');
+ }
+
+ text = text.trim();
+ var optExpr = /^Optional\.|(?:, )?Optional$/;
+ var optional = text.match(optExpr);
+ if (optional) {
+ item.optional = true;
+ text = text.replace(optExpr, '');
+ }
+
+ text = text.replace(/^\s*-\s*/, '');
+ text = text.trim();
+ if (text) item.desc = text;
+}
+
+
+function finishSection(section, parent) {
+ if (!section || !parent) {
+ throw new Error('Invalid finishSection call\n'+
+ JSON.stringify(section) + '\n' +
+ JSON.stringify(parent));
+ }
+
+ if (!section.type) {
+ section.type = 'module';
+ if (parent && (parent.type === 'misc')) {
+ section.type = 'misc';
+ }
+ section.displayName = section.name;
+ section.name = section.name.toLowerCase()
+ .trim().replace(/\s+/g, '_');
+ }
+
+ if (section.desc && Array.isArray(section.desc)) {
+ section.desc.links = section.desc.links || [];
+ section.desc = marked.parser(section.desc);
+ }
+
+ if (!section.list) section.list = [];
+ processList(section);
+
+ // classes sometimes have various 'ctor' children
+ // which are actually just descriptions of a constructor
+ // class signature.
+ // Merge them into the parent.
+ if (section.type === 'class' && section.ctors) {
+ section.signatures = section.signatures || [];
+ var sigs = section.signatures;
+ section.ctors.forEach(function(ctor) {
+ ctor.signatures = ctor.signatures || [{}];
+ ctor.signatures.forEach(function(sig) {
+ sig.desc = ctor.desc;
+ });
+ sigs.push.apply(sigs, ctor.signatures);
+ });
+ delete section.ctors;
+ }
+
+ // properties are a bit special.
+ // their "type" is the type of object, not "property"
+ if (section.properties) {
+ section.properties.forEach(function (p) {
+ if (p.typeof) p.type = p.typeof;
+ else delete p.type;
+ delete p.typeof;
+ });
+ }
+
+ // handle clones
+ if (section.clone) {
+ var clone = section.clone;
+ delete section.clone;
+ delete clone.clone;
+ deepCopy(section, clone);
+ finishSection(clone, parent);
+ }
+
+ var plur;
+ if (section.type.slice(-1) === 's') {
+ plur = section.type + 'es';
+ } else if (section.type.slice(-1) === 'y') {
+ plur = section.type.replace(/y$/, 'ies');
+ } else {
+ plur = section.type + 's';
+ }
+
+ // if the parent's type is 'misc', then it's just a random
+ // collection of stuff, like the "globals" section.
+ // Make the children top-level items.
+ if (section.type === 'misc') {
+ Object.keys(section).forEach(function(k) {
+ switch (k) {
+ case 'textRaw':
+ case 'name':
+ case 'type':
+ case 'desc':
+ case 'miscs':
+ return;
+ default:
+ if (parent.type === 'misc') {
+ return;
+ }
+ if (Array.isArray(k) && parent[k]) {
+ parent[k] = parent[k].concat(section[k]);
+ } else if (!parent[k]) {
+ parent[k] = section[k];
+ } else {
+ // parent already has, and it's not an array.
+ return;
+ }
+ }
+ });
+ }
+
+ parent[plur] = parent[plur] || [];
+ parent[plur].push(section);
+}
+
+
+// Not a general purpose deep copy.
+// But sufficient for these basic things.
+function deepCopy(src, dest) {
+ Object.keys(src).filter(function(k) {
+ return !dest.hasOwnProperty(k);
+ }).forEach(function(k) {
+ dest[k] = deepCopy_(src[k]);
+ });
+}
+
+function deepCopy_(src) {
+ if (!src) return src;
+ if (Array.isArray(src)) {
+ var c = new Array(src.length);
+ src.forEach(function(v, i) {
+ c[i] = deepCopy_(v);
+ });
+ return c;
+ }
+ if (typeof src === 'object') {
+ var c = {};
+ Object.keys(src).forEach(function(k) {
+ c[k] = deepCopy_(src[k]);
+ });
+ return c;
+ }
+ return src;
+}
+
+
+// these parse out the contents of an H# tag
+var eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i;
+var classExpr = /^Class:\s*([^ ]+).*?$/i;
+var propExpr = /^(?:property:?\s*)?[^\.]+\.([^ \.\(\)]+)\s*?$/i;
+var braceExpr = /^(?:property:?\s*)?[^\.\[]+(\[[^\]]+\])\s*?$/i;
+var classMethExpr =
+ /^class\s*method\s*:?[^\.]+\.([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
+var methExpr =
+ /^(?:method:?\s*)?(?:[^\.]+\.)?([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
+var newExpr = /^new ([A-Z][a-z]+)\([^\)]*\)\s*?$/;
+var paramExpr = /\((.*)\);?$/;
+
+function newSection(tok) {
+ var section = {};
+ // infer the type from the text.
+ var text = section.textRaw = tok.text;
+ if (text.match(eventExpr)) {
+ section.type = 'event';
+ section.name = text.replace(eventExpr, '$1');
+ } else if (text.match(classExpr)) {
+ section.type = 'class';
+ section.name = text.replace(classExpr, '$1');
+ } else if (text.match(braceExpr)) {
+ section.type = 'property';
+ section.name = text.replace(braceExpr, '$1');
+ } else if (text.match(propExpr)) {
+ section.type = 'property';
+ section.name = text.replace(propExpr, '$1');
+ } else if (text.match(classMethExpr)) {
+ section.type = 'classMethod';
+ section.name = text.replace(classMethExpr, '$1');
+ } else if (text.match(methExpr)) {
+ section.type = 'method';
+ section.name = text.replace(methExpr, '$1');
+ } else if (text.match(newExpr)) {
+ section.type = 'ctor';
+ section.name = text.replace(newExpr, '$1');
+ } else {
+ section.name = text;
+ }
+ return section;
+}
diff --git a/tools/doc/node_modules/.bin/marked b/tools/doc/node_modules/.bin/marked
new file mode 120000
index 00000000000..a8d872e9dc1
--- /dev/null
+++ b/tools/doc/node_modules/.bin/marked
@@ -0,0 +1 @@
+../marked/bin/marked
\ No newline at end of file
diff --git a/tools/doc/node_modules/marked/.npmignore b/tools/doc/node_modules/marked/.npmignore
new file mode 100644
index 00000000000..3fb773c0342
--- /dev/null
+++ b/tools/doc/node_modules/marked/.npmignore
@@ -0,0 +1,2 @@
+.git*
+test/
diff --git a/tools/doc/node_modules/marked/LICENSE b/tools/doc/node_modules/marked/LICENSE
new file mode 100644
index 00000000000..40597477c63
--- /dev/null
+++ b/tools/doc/node_modules/marked/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2011-2012, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/tools/doc/node_modules/marked/Makefile b/tools/doc/node_modules/marked/Makefile
new file mode 100644
index 00000000000..76904000b5e
--- /dev/null
+++ b/tools/doc/node_modules/marked/Makefile
@@ -0,0 +1,9 @@
+all:
+ @cp lib/marked.js marked.js
+ @uglifyjs -o marked.min.js marked.js
+
+clean:
+ @rm marked.js
+ @rm marked.min.js
+
+.PHONY: clean all
diff --git a/tools/doc/node_modules/marked/README.md b/tools/doc/node_modules/marked/README.md
new file mode 100644
index 00000000000..1a0747c0d7e
--- /dev/null
+++ b/tools/doc/node_modules/marked/README.md
@@ -0,0 +1,135 @@
+# marked
+
+A full-featured markdown parser and compiler.
+Built for speed.
+
+## Benchmarks
+
+node v0.4.x
+
+``` bash
+$ node test --bench
+marked completed in 12071ms.
+showdown (reuse converter) completed in 27387ms.
+showdown (new converter) completed in 75617ms.
+markdown-js completed in 70069ms.
+```
+
+node v0.6.x
+
+``` bash
+$ node test --bench
+marked completed in 6485ms.
+marked (with gfm) completed in 7466ms.
+discount completed in 7169ms.
+showdown (reuse converter) completed in 15937ms.
+showdown (new converter) completed in 18279ms.
+markdown-js completed in 23572ms.
+```
+
+__Marked is now faster than Discount, which is written in C.__
+
+For those feeling skeptical: These benchmarks run the entire markdown test suite
+1000 times. The test suite tests every feature. It doesn't cater to specific
+aspects.
+
+Benchmarks for other engines to come (?).
+
+## Install
+
+``` bash
+$ npm install marked
+```
+
+## Another javascript markdown parser
+
+The point of marked was to create a markdown compiler where it was possible to
+frequently parse huge chunks of markdown without having to worry about
+caching the compiled output somehow...or blocking for an unnecesarily long time.
+
+marked is very concise and still implements all markdown features. It is also
+now fully compatible with the client-side.
+
+marked more or less passes the official markdown test suite in its
+entirety. This is important because a surprising number of markdown compilers
+cannot pass more than a few tests. It was very difficult to get marked as
+compliant as it is. It could have cut corners in several areas for the sake
+of performance, but did not in order to be exactly what you expect in terms
+of a markdown rendering. In fact, this is why marked could be considered at a
+disadvantage in the benchmarks above.
+
+Along with implementing every markdown feature, marked also implements
+[GFM features](http://github.github.com/github-flavored-markdown/).
+
+## Usage
+
+``` js
+var marked = require('marked');
+console.log(marked('i am using __markdown__.'));
+```
+
+You also have direct access to the lexer and parser if you so desire.
+
+``` js
+var tokens = marked.lexer(str);
+console.log(marked.parser(tokens));
+```
+
+``` bash
+$ node
+> require('marked').lexer('> i am using marked.')
+[ { type: 'blockquote_start' },
+ { type: 'text', text: ' i am using marked.' },
+ { type: 'blockquote_end' },
+ links: {} ]
+```
+
+## CLI
+
+``` bash
+$ marked -o hello.html
+hello world
+^D
+$ cat hello.html
+
");
-
- return toc.join("");
-}
-
-
-var includeExpr = /^@include\s+([A-Za-z0-9-_]+)(?:\.)?([a-zA-Z]*)$/gmi;
-// Allow including other pages in the data.
-function loadIncludes(data, current_file) {
- return data.replace(includeExpr, function(src, name, ext) {
- try {
- var include_path = path.join(current_file, "../", name+"."+(ext || "markdown"))
- return loadIncludes(fs.readFileSync(include_path, "utf8"), current_file);
- } catch(e) {
- return "";
- }
- });
-}
-
-
-function convertData(data) {
- // Convert it to HTML from Markdown
- var html = markdown.toHTML(markdown.parse(data), {xhtml:true})
- .replace(/<\/hr>/g, "")
- .replace(/(\([^<]+)(\<\/h[1-6]\>)/gmi, function(o, ts, c, te) {
- return ts+' id="'+formatIdString(c)+'">'+c+te;
- })
- .replace(/(\]+\>)([^<]+)(\<\/h[2-4]\>)/gmi,
- function(o, ts, c, te) {
- var mark = ' ' +
- '↑' +
- '#';
-
- return ts+c+mark+te;
- });
-
- return html;
-}
-
-
-if (argc > 3) {
- var filename = argv[3],
- output = template,
- html;
-
- fs.readFile(filename, "utf8", function(err, data) {
- if (err) throw err;
-
- // go recursion.
- data = loadIncludes(data, filename);
- // go markdown.
- html = convertData(data);
- filename = path.basename(filename, '.markdown');
- output = output.replace(/{{filename}}/g, filename);
-
- if (filename != "_toc" && filename != "index") {
- if (data) {
- html = generateToc(data) + "\n" + html;
- }
-
- output = output.replace("{{section}}", filename+" - ")
- } else {
- if (filename === "index") {
- html = '
' + html + '
';
- }
- output = output.replace("{{section}}", "");
- output = output.replace(/]*)>/, '');
- }
- if (html.length == 0) {
- html = "Sorry, this section is currently undocumented, \
-but we'll be working on it.";
- }
- output = output.replace("{{content}}", html);
-
- if (argc > 4) {
- fs.writeFile(argv[4], output);
- } else {
- process.stdout.write(output);
- }
- });
-}
diff --git a/tools/doctool/markdown.js b/tools/doctool/markdown.js
deleted file mode 100644
index 3caa2e29579..00000000000
--- a/tools/doctool/markdown.js
+++ /dev/null
@@ -1,1448 +0,0 @@
-// Released under MIT license
-// Copyright (c) 2009-2010 Dominic Baggott
-// Copyright (c) 2009-2010 Ash Berlin
-
-(function( expose ) {
-
-/**
- * class Markdown
- *
- * Markdown processing in Javascript done right. We have very particular views
- * on what constitutes 'right' which include:
- *
- * - produces well-formed HTML (this means that em and strong nesting is
- * important)
- *
- * - has an intermediate representation to allow processing of parsed data (We
- * in fact have two, both as [JsonML]: a markdown tree and an HTML tree).
- *
- * - is easily extensible to add new dialects without having to rewrite the
- * entire parsing mechanics
- *
- * - has a good test suite
- *
- * This implementation fulfills all of these (except that the test suite could
- * do with expanding to automatically run all the fixtures from other Markdown
- * implementations.)
- *
- * ##### Intermediate Representation
- *
- * *TODO* Talk about this :) Its JsonML, but document the node names we use.
- *
- * [JsonML]: http://jsonml.org/ "JSON Markup Language"
- **/
-var Markdown = expose.Markdown = function Markdown(dialect) {
- switch (typeof dialect) {
- case "undefined":
- this.dialect = Markdown.dialects.Gruber;
- break;
- case "object":
- this.dialect = dialect;
- break;
- default:
- if (dialect in Markdown.dialects) {
- this.dialect = Markdown.dialects[dialect];
- }
- else {
- throw new Error("Unknown Markdown dialect '" + String(dialect) + "'");
- }
- break;
- }
- this.em_state = [];
- this.strong_state = [];
- this.debug_indent = "";
-}
-
-/**
- * parse( markdown, [dialect] ) -> JsonML
- * - markdown (String): markdown string to parse
- * - dialect (String | Dialect): the dialect to use, defaults to gruber
- *
- * Parse `markdown` and return a markdown document as a Markdown.JsonML tree.
- **/
-expose.parse = function( source, dialect ) {
- // dialect will default if undefined
- var md = new Markdown( dialect );
- return md.toTree( source );
-}
-
-/**
- * toHTML( markdown ) -> String
- * toHTML( md_tree ) -> String
- * - markdown (String): markdown string to parse
- * - md_tree (Markdown.JsonML): parsed markdown tree
- *
- * Take markdown (either as a string or as a JsonML tree) and run it through
- * [[toHTMLTree]] then turn it into a well-formated HTML fragment.
- **/
-expose.toHTML = function toHTML( source ) {
- var input = expose.toHTMLTree( source );
-
- return expose.renderJsonML( input );
-}
-
-/**
- * toHTMLTree( markdown, [dialect] ) -> JsonML
- * toHTMLTree( md_tree ) -> JsonML
- * - markdown (String): markdown string to parse
- * - dialect (String | Dialect): the dialect to use, defaults to gruber
- * - md_tree (Markdown.JsonML): parsed markdown tree
- *
- * Turn markdown into HTML, represented as a JsonML tree. If a string is given
- * to this function, it is first parsed into a markdown tree by calling
- * [[parse]].
- **/
-expose.toHTMLTree = function toHTMLTree( input, dialect ) {
- // convert string input to an MD tree
- if ( typeof input ==="string" ) input = this.parse( input, dialect );
-
- // Now convert the MD tree to an HTML tree
-
- // remove references from the tree
- var attrs = extract_attr( input ),
- refs = {};
-
- if ( attrs && attrs.references ) {
- refs = attrs.references;
- }
-
- var html = convert_tree_to_html( input, refs );
- merge_text_nodes( html );
- return html;
-}
-
-var mk_block = Markdown.mk_block = function(block, trail, line) {
- // Be helpful for default case in tests.
- if ( arguments.length == 1 ) trail = "\n\n";
-
- var s = new String(block);
- s.trailing = trail;
- // To make it clear its not just a string
- s.toSource = function() {
- return "Markdown.mk_block( " +
- uneval(block) +
- ", " +
- uneval(trail) +
- ", " +
- uneval(line) +
- " )"
- }
-
- if (line != undefined)
- s.lineNumber = line;
-
- return s;
-}
-
-function count_lines( str ) {
- var n = 0, i = -1;;
- while ( ( i = str.indexOf('\n', i+1) ) != -1) n++;
- return n;
-}
-
-// Internal - split source into rough blocks
-Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) {
- // [\s\S] matches _anything_ (newline or space)
- var re = /([\s\S]+?)($|\n(?:\s*\n|$)+)/g,
- blocks = [],
- m;
-
- var line_no = 1;
-
- if ( ( m = /^(\s*\n)/.exec(input) ) != null ) {
- // skip (but count) leading blank lines
- line_no += count_lines( m[0] );
- re.lastIndex = m[0].length;
- }
-
- while ( ( m = re.exec(input) ) != null ) {
- blocks.push( mk_block( m[1], m[2], line_no ) );
- line_no += count_lines( m[0] );
- }
-
- return blocks;
-}
-
-/**
- * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ]
- * - block (String): the block to process
- * - next (Array): the following blocks
- *
- * Process `block` and return an array of JsonML nodes representing `block`.
- *
- * It does this by asking each block level function in the dialect to process
- * the block until one can. Succesful handling is indicated by returning an
- * array (with zero or more JsonML nodes), failure by a false value.
- *
- * Blocks handlers are responsible for calling [[Markdown#processInline]]
- * themselves as appropriate.
- *
- * If the blocks were split incorrectly or adjacent blocks need collapsing you
- * can adjust `next` in place using shift/splice etc.
- *
- * If any of this default behaviour is not right for the dialect, you can
- * define a `__call__` method on the dialect that will get invoked to handle
- * the block processing.
- */
-Markdown.prototype.processBlock = function processBlock( block, next ) {
- var cbs = this.dialect.block,
- ord = cbs.__order__;
-
- if ( "__call__" in cbs ) {
- return cvs.__call__.call(this, block, next);
- }
-
- for ( var i = 0; i < ord.length; i++ ) {
- //D:this.debug( "Testing", ord[i] );
- var res = cbs[ ord[i] ].call( this, block, next );
- if ( res ) {
- //D:this.debug(" matched");
- if ( !res instanceof Array || ( res.length > 0 && !( res[0] instanceof Array ) ) )
- this.debug(ord[i], "didn't return a proper array");
- //D:this.debug( "" );
- return res;
- }
- }
-
- // Uhoh! no match! Should we throw an error?
- return [];
-}
-
-Markdown.prototype.processInline = function processInline( block ) {
- return this.dialect.inline.__call__.call( this, String( block ) );
-}
-
-/**
- * Markdown#toTree( source ) -> JsonML
- * - source (String): markdown source to parse
- *
- * Parse `source` into a JsonML tree representing the markdown document.
- **/
-// custom_tree means set this.tree to `custom_tree` and restore old value on return
-Markdown.prototype.toTree = function toTree( source, custom_root ) {
- var blocks = source instanceof Array
- ? source
- : this.split_blocks( source );
-
- // Make tree a member variable so its easier to mess with in extensions
- var old_tree = this.tree;
- try {
- this.tree = custom_root || this.tree || [ "markdown" ];
-
- blocks:
- while ( blocks.length ) {
- var b = this.processBlock( blocks.shift(), blocks );
-
- // Reference blocks and the like won't return any content
- if ( !b.length ) continue blocks;
-
- this.tree.push.apply( this.tree, b );
- }
- return this.tree;
- }
- finally {
- if ( custom_root )
- this.tree = old_tree;
- }
-
-}
-
-// Noop by default
-Markdown.prototype.debug = function () {
- var args = Array.prototype.slice.call( arguments);
- args.unshift(this.debug_indent);
- print.apply( print, args );
-}
-
-Markdown.prototype.loop_re_over_block = function( re, block, cb ) {
- // Dont use /g regexps with this
- var m,
- b = block.valueOf();
-
- while ( b.length && (m = re.exec(b) ) != null) {
- b = b.substr( m[0].length );
- cb.call(this, m);
- }
- return b;
-}
-
-/**
- * Markdown.dialects
- *
- * Namespace of built-in dialects.
- **/
-Markdown.dialects = {};
-
-/**
- * Markdown.dialects.Gruber
- *
- * The default dialect that follows the rules set out by John Gruber's
- * markdown.pl as closely as possible. Well actually we follow the behaviour of
- * that script which in some places is not exactly what the syntax web page
- * says.
- **/
-Markdown.dialects.Gruber = {
- block: {
- atxHeader: function atxHeader( block, next ) {
- var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ );
-
- if ( !m ) return undefined;
-
- var header = [ "header", { level: m[ 1 ].length }, m[ 2 ] ];
-
- if ( m[0].length < block.length )
- next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
-
- return [ header ];
- },
-
- setextHeader: function setextHeader( block, next ) {
- var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ );
-
- if ( !m ) return undefined;
-
- var level = ( m[ 2 ] === "=" ) ? 1 : 2;
- var header = [ "header", { level : level }, m[ 1 ] ];
-
- if ( m[0].length < block.length )
- next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
-
- return [ header ];
- },
-
- code: function code( block, next ) {
- // | Foo
- // |bar
- // should be a code block followed by a paragraph. Fun
- //
- // There might also be adjacent code block to merge.
-
- var ret = [],
- re = /^(?: {0,3}\t| {4})(.*)\n?/,
- lines;
-
- // 4 spaces + content
- var m = block.match( re );
-
- if ( !m ) return undefined;
-
- block_search:
- do {
- // Now pull out the rest of the lines
- var b = this.loop_re_over_block(
- re, block.valueOf(), function( m ) { ret.push( m[1] ) } );
-
- if (b.length) {
- // Case alluded to in first comment. push it back on as a new block
- next.unshift( mk_block(b, block.trailing) );
- break block_search;
- }
- else if (next.length) {
- // Check the next block - it might be code too
- var m = next[0].match( re );
-
- if ( !m ) break block_search;
-
- // Pull how how many blanks lines follow - minus two to account for .join
- ret.push ( block.trailing.replace(/[^\n]/g, '').substring(2) );
-
- block = next.shift();
- }
- else
- break block_search;
- } while (true);
-
- return [ [ "code_block", ret.join("\n") ] ];
- },
-
- horizRule: function horizRule( block, next ) {
- // this needs to find any hr in the block to handle abutting blocks
- var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ );
-
- if ( !m ) {
- return undefined;
- }
-
- var jsonml = [ [ "hr" ] ];
-
- // if there's a leading abutting block, process it
- if ( m[ 1 ] ) {
- jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
- }
-
- // if there's a trailing abutting block, stick it into next
- if ( m[ 3 ] ) {
- next.unshift( mk_block( m[ 3 ] ) );
- }
-
- return jsonml;
- },
-
- // There are two types of lists. Tight and loose. Tight lists have no whitespace
- // between the items (and result in text just in the
) and loose lists,
- // which have an empty line between list items, resulting in (one or more)
- // paragraphs inside the
.
- //
- // There are all sorts weird edge cases about the original markdown.pl's
- // handling of lists:
- //
- // * Nested lists are supposed to be indented by four chars per level. But
- // if they aren't, you can get a nested list by indenting by less than
- // four so long as the indent doesn't match an indent of an existing list
- // item in the 'nest stack'.
- //
- // * The type of the list (bullet or number) is controlled just by the
- // first item at the indent. Subsequent changes are ignored unless they
- // are for nested lists
- //
- lists: (function( ) {
- // Use a closure to hide a few variables.
- var any_list = "[*+-]|\\d\\.",
- bullet_list = /[*+-]/,
- number_list = /\d+\./,
- // Capture leading indent as it matters for determining nested lists.
- is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ),
- indent_re = "(?: {0,3}\\t| {4})";
-
- // TODO: Cache this regexp for certain depths.
- // Create a regexp suitable for matching an li for a given stack depth
- function regex_for_depth( depth ) {
-
- return new RegExp(
- // m[1] = indent, m[2] = list_type
- "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" +
- // m[3] = cont
- "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})"
- );
- }
- function expand_tab( input ) {
- return input.replace( / {0,3}\t/g, " " );
- }
-
- // Add inline content `inline` to `li`. inline comes from processInline
- // so is an array of content
- function add(li, loose, inline, nl) {
- if (loose) {
- li.push( [ "para" ].concat(inline) );
- return;
- }
- // Hmmm, should this be any block level element or just paras?
- var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para"
- ? li[li.length -1]
- : li;
-
- // If there is already some content in this list, add the new line in
- if (nl && li.length > 1) inline.unshift(nl);
-
- for (var i=0; i < inline.length; i++) {
- var what = inline[i],
- is_str = typeof what == "string";
- if (is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" )
- {
- add_to[ add_to.length-1 ] += what;
- }
- else {
- add_to.push( what );
- }
- }
- }
-
- // contained means have an indent greater than the current one. On
- // *every* line in the block
- function get_contained_blocks( depth, blocks ) {
-
- var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ),
- replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"),
- ret = [];
-
- while ( blocks.length > 0 ) {
- if ( re.exec( blocks[0] ) ) {
- var b = blocks.shift(),
- // Now remove that indent
- x = b.replace( replace, "");
-
- ret.push( mk_block( x, b.trailing, b.lineNumber ) );
- }
- break;
- }
- return ret;
- }
-
- // passed to stack.forEach to turn list items up the stack into paras
- function paragraphify(s, i, stack) {
- var list = s.list;
- var last_li = list[list.length-1];
-
- if (last_li[1] instanceof Array && last_li[1][0] == "para") {
- return;
- }
- if (i+1 == stack.length) {
- // Last stack frame
- // Keep the same array, but replace the contents
- last_li.push( ["para"].concat( last_li.splice(1) ) );
- }
- else {
- var sublist = last_li.pop();
- last_li.push( ["para"].concat( last_li.splice(1) ), sublist );
- }
- }
-
- // The matcher function
- return function( block, next ) {
- var m = block.match( is_list_re );
- if ( !m ) return undefined;
-
- function make_list( m ) {
- var list = bullet_list.exec( m[2] )
- ? ["bulletlist"]
- : ["numberlist"];
-
- stack.push( { list: list, indent: m[1] } );
- return list;
- }
-
-
- var stack = [], // Stack of lists for nesting.
- list = make_list( m ),
- last_li,
- loose = false,
- ret = [ stack[0].list ];
-
- // Loop to search over block looking for inner block elements and loose lists
- loose_search:
- while( true ) {
- // Split into lines preserving new lines at end of line
- var lines = block.split( /(?=\n)/ );
-
- // We have to grab all lines for a li and call processInline on them
- // once as there are some inline things that can span lines.
- var li_accumulate = "";
-
- // Loop over the lines in this block looking for tight lists.
- tight_search:
- for (var line_no=0; line_no < lines.length; line_no++) {
- var nl = "",
- l = lines[line_no].replace(/^\n/, function(n) { nl = n; return "" });
-
- // TODO: really should cache this
- var line_re = regex_for_depth( stack.length );
-
- m = l.match( line_re );
- //print( "line:", uneval(l), "\nline match:", uneval(m) );
-
- // We have a list item
- if ( m[1] !== undefined ) {
- // Process the previous list item, if any
- if ( li_accumulate.length ) {
- add( last_li, loose, this.processInline( li_accumulate ), nl );
- // Loose mode will have been dealt with. Reset it
- loose = false;
- li_accumulate = "";
- }
-
- m[1] = expand_tab( m[1] );
- var wanted_depth = Math.floor(m[1].length/4)+1;
- //print( "want:", wanted_depth, "stack:", stack.length);
- if ( wanted_depth > stack.length ) {
- // Deep enough for a nested list outright
- //print ( "new nested list" );
- list = make_list( m );
- last_li.push( list );
- last_li = list[1] = [ "listitem" ];
- }
- else {
- // We aren't deep enough to be strictly a new level. This is
- // where Md.pl goes nuts. If the indent matches a level in the
- // stack, put it there, else put it one deeper then the
- // wanted_depth deserves.
- var found = stack.some(function(s, i) {
- if ( s.indent != m[1] ) return false;
- list = s.list; // Found the level we want
- stack.splice(i+1); // Remove the others
- //print("found");
- return true; // And stop looping
- });
-
- if (!found) {
- //print("not found. l:", uneval(l));
- wanted_depth++;
- if (wanted_depth <= stack.length) {
- stack.splice(wanted_depth);
- //print("Desired depth now", wanted_depth, "stack:", stack.length);
- list = stack[wanted_depth-1].list;
- //print("list:", uneval(list) );
- }
- else {
- //print ("made new stack for messy indent");
- list = make_list(m);
- last_li.push(list);
- }
- }
-
- //print( uneval(list), "last", list === stack[stack.length-1].list );
- last_li = [ "listitem" ];
- list.push(last_li);
- } // end depth of shenegains
- nl = "";
- }
-
- // Add content
- if (l.length > m[0].length) {
- li_accumulate += nl + l.substr( m[0].length );
- }
- } // tight_search
-
- if ( li_accumulate.length ) {
- add( last_li, loose, this.processInline( li_accumulate ), nl );
- // Loose mode will have been dealt with. Reset it
- loose = false;
- li_accumulate = "";
- }
-
- // Look at the next block - we might have a loose list. Or an extra
- // paragraph for the current li
- var contained = get_contained_blocks( stack.length, next );
-
- // Deal with code blocks or properly nested lists
- if (contained.length > 0) {
- // Make sure all listitems up the stack are paragraphs
- stack.forEach( paragraphify, this );
-
- last_li.push.apply( last_li, this.toTree( contained, [] ) );
- }
-
- var next_block = next[0] && next[0].valueOf() || "";
-
- if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) {
- block = next.shift();
-
- // Check for an HR following a list: features/lists/hr_abutting
- var hr = this.dialect.block.horizRule( block, next );
-
- if (hr) {
- ret.push.apply(ret, hr);
- break;
- }
-
- // Make sure all listitems up the stack are paragraphs
- stack.forEach( paragraphify , this );
-
- loose = true;
- continue loose_search;
- }
- break;
- } // loose_search
-
- return ret;
- }
- })(),
-
- blockquote: function blockquote( block, next ) {
- if ( !block.match( /^>/m ) )
- return undefined;
-
- var jsonml = [];
-
- // separate out the leading abutting block, if any
- if ( block[ 0 ] != ">" ) {
- var lines = block.split( /\n/ ),
- prev = [];
-
- // keep shifting lines until you find a crotchet
- while ( lines.length && lines[ 0 ][ 0 ] != ">" ) {
- prev.push( lines.shift() );
- }
-
- // reassemble!
- block = lines.join( "\n" );
- jsonml.push.apply( jsonml, this.processBlock( prev.join( "\n" ), [] ) );
- }
-
- // if the next block is also a blockquote merge it in
- while ( next.length && next[ 0 ][ 0 ] == ">" ) {
- var b = next.shift();
- block += block.trailing + b;
- block.trailing = b.trailing;
- }
-
- // Strip off the leading "> " and re-process as a block.
- var input = block.replace( /^> ?/gm, '' ),
- old_tree = this.tree;
- jsonml.push( this.toTree( input, [ "blockquote" ] ) );
-
- return jsonml;
- },
-
- referenceDefn: function referenceDefn( block, next) {
- var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;
- // interesting matches are [ , ref_id, url, , title, title ]
-
- if ( !block.match(re) )
- return undefined;
-
- // make an attribute node if it doesn't exist
- if ( !extract_attr( this.tree ) ) {
- this.tree.splice( 1, 0, {} );
- }
-
- var attrs = extract_attr( this.tree );
-
- // make a references hash if it doesn't exist
- if ( attrs.references === undefined ) {
- attrs.references = {};
- }
-
- var b = this.loop_re_over_block(re, block, function( m ) {
-
- if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' )
- m[2] = m[2].substring( 1, m[2].length - 1 );
-
- var ref = attrs.references[ m[1].toLowerCase() ] = {
- href: m[2]
- };
-
- if (m[4] !== undefined)
- ref.title = m[4];
- else if (m[5] !== undefined)
- ref.title = m[5];
-
- } );
-
- if (b.length)
- next.unshift( mk_block( b, block.trailing ) );
-
- return [];
- },
-
- para: function para( block, next ) {
- // everything's a para!
- return [ ["para"].concat( this.processInline( block ) ) ];
- }
- }
-}
-
-Markdown.dialects.Gruber.inline = {
- __call__: function inline( text, patterns ) {
- // Hmmm - should this function be directly in Md#processInline, or
- // conversely, should Md#processBlock be moved into block.__call__ too
- var out = [ ],
- m,
- // Look for the next occurange of a special character/pattern
- re = new RegExp( "([\\s\\S]*?)(" + (patterns.source || patterns) + ")", "g" ),
- lastIndex = 0;
-
- //D:var self = this;
- //D:self.debug("processInline:", uneval(text) );
- function add(x) {
- //D:self.debug(" adding output", uneval(x));
- if (typeof x == "string" && typeof out[out.length-1] == "string")
- out[ out.length-1 ] += x;
- else
- out.push(x);
- }
-
- while ( ( m = re.exec(text) ) != null) {
- if ( m[1] ) add( m[1] ); // Some un-interesting text matched
- else m[1] = { length: 0 }; // Or there was none, but make m[1].length == 0
-
- var res;
- if ( m[2] in this.dialect.inline ) {
- res = this.dialect.inline[ m[2] ].call(
- this,
- text.substr( m.index + m[1].length ), m, out );
- }
- // Default for now to make dev easier. just slurp special and output it.
- res = res || [ m[2].length, m[2] ];
-
- var len = res.shift();
- // Update how much input was consumed
- re.lastIndex += ( len - m[2].length );
-
- // Add children
- res.forEach(add);
-
- lastIndex = re.lastIndex;
- }
-
- // Add last 'boring' chunk
- if ( text.length > lastIndex )
- add( text.substr( lastIndex ) );
-
- return out;
- },
-
- "\\": function escaped( text ) {
- // [ length of input processed, node/children to add... ]
- // Only esacape: \ ` * _ { } [ ] ( ) # * + - . !
- if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\-]/ ) )
- return [ 2, text[1] ];
- else
- // Not an esacpe
- return [ 1, "\\" ];
- },
-
- "
- // 1 2 3 4 <--- captures
- var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*(\S*)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
-
- if ( m ) {
- if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' )
- m[2] = m[2].substring( 1, m[2].length - 1 );
-
- m[2] == this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
-
- var attrs = { alt: m[1], href: m[2] || "" };
- if ( m[4] !== undefined)
- attrs.title = m[4];
-
- return [ m[0].length, [ "img", attrs ] ];
- }
-
- // ![Alt text][id]
- m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ );
-
- if ( m ) {
- // We can't check if the reference is known here as it likely wont be
- // found till after. Check it in md tree->hmtl tree conversion
- return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), text: m[0] } ] ];
- }
-
- // Just consume the '!['
- return [ 2, "![" ];
- },
-
- "[": function link( text ) {
- // [link text](/path/to/img.jpg "Optional title")
- // 1 2 3 4 <--- captures
- var m = text.match( /^\[([\s\S]*?)\][ \t]*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
-
- if ( m ) {
- if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' )
- m[2] = m[2].substring( 1, m[2].length - 1 );
-
- // Process escapes only
- m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
-
- var attrs = { href: m[2] || "" };
- if ( m[4] !== undefined)
- attrs.title = m[4];
-
- return [ m[0].length, [ "link", attrs, m[1] ] ];
- }
-
- // [Alt text][id]
- // [Alt text] [id]
- // [id]
- m = text.match( /^\[([\s\S]*?)\](?: ?\[(.*?)\])?/ );
-
- if ( m ) {
- // [id] case, text == id
- if ( m[2] === undefined || m[2] === "" ) m[2] = m[1];
-
- // We can't check if the reference is known here as it likely wont be
- // found till after. Check it in md tree->hmtl tree conversion.
- // Store the original so that conversion can revert if the ref isn't found.
- return [
- m[ 0 ].length,
- [
- "link_ref",
- {
- ref: m[ 2 ].toLowerCase(),
- original: m[ 0 ]
- },
- m[ 1 ]
- ]
- ];
- }
-
- // Just consume the '['
- return [ 1, "[" ];
- },
-
-
- "<": function autoLink( text ) {
- var m;
-
- if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) {
- if ( m[3] ) {
- return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ];
-
- }
- else if ( m[2] == "mailto" ) {
- return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ];
- }
- else
- return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ];
- }
-
- return [ 1, "<" ];
- },
-
- "`": function inlineCode( text ) {
- // Inline code block. as many backticks as you like to start it
- // Always skip over the opening ticks.
- var m = text.match( /(`+)(([\s\S]*?)\1)/ );
-
- if ( m && m[2] )
- return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ];
- else {
- // TODO: No matching end code found - warn!
- return [ 1, "`" ];
- }
- },
-
- " \n": function lineBreak( text ) {
- return [ 3, [ "linebreak" ] ];
- }
-
-}
-
-// Meta Helper/generator method for em and strong handling
-function strong_em( tag, md ) {
-
- var state_slot = tag + "_state",
- other_slot = tag == "strong" ? "em_state" : "strong_state";
-
- function CloseTag(len) {
- this.len_after = len;
- this.name = "close_" + md;
- }
-
- return function ( text, orig_match ) {
-
- if (this[state_slot][0] == md) {
- // Most recent em is of this type
- //D:this.debug("closing", md);
- this[state_slot].shift();
-
- // "Consume" everything to go back to the recrusion in the else-block below
- return[ text.length, new CloseTag(text.length-md.length) ];
- }
- else {
- // Store a clone of the em/strong states
- var other = this[other_slot].slice(),
- state = this[state_slot].slice();
-
- this[state_slot].unshift(md);
-
- //D:this.debug_indent += " ";
-
- // Recurse
- var res = this.processInline( text.substr( md.length ) );
- //D:this.debug_indent = this.debug_indent.substr(2);
-
- var last = res[res.length - 1];
-
- //D:this.debug("processInline from", tag + ": ", uneval( res ) );
-
- var check = this[state_slot].shift();
- if (last instanceof CloseTag) {
- res.pop();
- // We matched! Huzzah.
- var consumed = text.length - last.len_after;
- return [ consumed, [ tag ].concat(res) ];
- }
- else {
- // Restore the state of the other kind. We might have mistakenly closed it.
- this[other_slot] = other;
- this[state_slot] = state;
-
- // We can't reuse the processed result as it could have wrong parsing contexts in it.
- return [ md.length, md ];
- }
- }
- } // End returned function
-}
-
-Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**");
-Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__");
-Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*");
-Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_");
-
-
-// Build default order from insertion order.
-Markdown.buildBlockOrder = function(d) {
- var ord = [];
- for ( var i in d ) {
- if ( i == "__order__" || i == "__call__" ) continue;
- ord.push( i );
- }
- d.__order__ = ord;
-}
-
-// Build patterns for inline matcher
-Markdown.buildInlinePatterns = function(d) {
- var patterns = [];
-
- for ( var i in d ) {
- if (i == "__call__") continue;
- var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" )
- .replace( /\n/, "\\n" );
- patterns.push( i.length == 1 ? l : "(?:" + l + ")" );
- }
-
- patterns = patterns.join("|");
- //print("patterns:", uneval( patterns ) );
-
- var fn = d.__call__;
- d.__call__ = function(text, pattern) {
- if (pattern != undefined)
- return fn.call(this, text, pattern);
- else
- return fn.call(this, text, patterns);
- }
-}
-
-// Helper function to make sub-classing a dialect easier
-Markdown.subclassDialect = function( d ) {
- function Block() {};
- Block.prototype = d.block;
- function Inline() {};
- Inline.prototype = d.inline;
-
- return { block: new Block(), inline: new Inline() };
-}
-
-Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block );
-Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline );
-
-Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber );
-
-Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) {
- // we're only interested in the first block
- if ( block.lineNumber > 1 ) return undefined;
-
- // document_meta blocks consist of one or more lines of `Key: Value\n`
- if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined;
-
- // make an attribute node if it doesn't exist
- if ( !extract_attr( this.tree ) ) {
- this.tree.splice( 1, 0, {} );
- }
-
- var pairs = block.split( /\n/ );
- for ( p in pairs ) {
- var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ),
- key = m[ 1 ].toLowerCase(),
- value = m[ 2 ];
-
- this.tree[ 1 ][ key ] = value;
- }
-
- // document_meta produces no content!
- return [];
-}
-
-Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) {
- // check if the last line of the block is an meta hash
- var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ );
- if ( !m ) return undefined;
-
- // process the meta hash
- var attr = process_meta_hash( m[ 2 ] );
-
- // if we matched ^ then we need to apply meta to the previous block
- if ( m[ 1 ] === "" ) {
- var node = this.tree[ this.tree.length - 1 ],
- hash = extract_attr( node );
-
- // if the node is a string (rather than JsonML), bail
- if ( typeof node === "string" ) return undefined;
-
- // create the attribute hash if it doesn't exist
- if ( !hash ) {
- hash = {};
- node.splice( 1, 0, hash );
- }
-
- // add the attributes in
- for ( a in attr ) {
- hash[ a ] = attr[ a ];
- }
-
- // return nothing so the meta hash is removed
- return [];
- }
-
- // pull the meta hash off the block and process what's left
- var b = block.replace( /\n.*$/, "" ),
- result = this.processBlock( b, [] );
-
- // get or make the attributes hash
- var hash = extract_attr( result[ 0 ] );
- if ( !hash ) {
- hash = {};
- result[ 0 ].splice( 1, 0, hash );
- }
-
- // attach the attributes to the block
- for ( a in attr ) {
- hash[ a ] = attr[ a ];
- }
-
- return result;
-}
-
-Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) {
- // one or more terms followed by one or more definitions, in a single block
- var tight = /^((?:[^\s:].*\n)+):\s+([^]+)$/,
- list = [ "dl" ];
-
- // see if we're dealing with a tight or loose block
- if ( ( m = block.match( tight ) ) ) {
- // pull subsequent tight DL blocks out of `next`
- var blocks = [ block ];
- while ( next.length && tight.exec( next[ 0 ] ) ) {
- blocks.push( next.shift() );
- }
-
- for ( var b = 0; b < blocks.length; ++b ) {
- var m = blocks[ b ].match( tight ),
- terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ),
- defns = m[ 2 ].split( /\n:\s+/ );
-
- // print( uneval( m ) );
-
- for ( var i = 0; i < terms.length; ++i ) {
- list.push( [ "dt", terms[ i ] ] );
- }
-
- for ( var i = 0; i < defns.length; ++i ) {
- // run inline processing over the definition
- list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) );
- }
- }
- }
- else {
- return undefined;
- }
-
- return [ list ];
-}
-
-Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) {
- if ( !out.length ) {
- return [ 2, "{:" ];
- }
-
- // get the preceeding element
- var before = out[ out.length - 1 ];
-
- if ( typeof before === "string" ) {
- return [ 2, "{:" ];
- }
-
- // match a meta hash
- var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ );
-
- // no match, false alarm
- if ( !m ) {
- return [ 2, "{:" ];
- }
-
- // attach the attributes to the preceeding element
- var meta = process_meta_hash( m[ 1 ] ),
- attr = extract_attr( before );
-
- if ( !attr ) {
- attr = {};
- before.splice( 1, 0, attr );
- }
-
- for ( var k in meta ) {
- attr[ k ] = meta[ k ];
- }
-
- // cut out the string and replace it with nothing
- return [ m[ 0 ].length, "" ];
-}
-
-Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block );
-Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline );
-
-function extract_attr( jsonml ) {
- return jsonml instanceof Array
- && jsonml.length > 1
- && typeof jsonml[ 1 ] === "object"
- && !( jsonml[ 1 ] instanceof Array )
- ? jsonml[ 1 ]
- : undefined;
-}
-
-function process_meta_hash( meta_string ) {
- var meta = split_meta_hash( meta_string ),
- attr = {};
-
- for ( var i = 0; i < meta.length; ++i ) {
- // id: #foo
- if ( /^#/.test( meta[ i ] ) ) {
- attr.id = meta[ i ].substring( 1 );
- }
- // class: .foo
- else if ( /^\./.test( meta[ i ] ) ) {
- // if class already exists, append the new one
- if ( attr['class'] ) {
- attr['class'] = attr['class'] + meta[ i ].replace( /./, " " );
- }
- else {
- attr['class'] = meta[ i ].substring( 1 );
- }
- }
- // attribute: foo=bar
- else if ( /=/.test( meta[ i ] ) ) {
- var s = meta[ i ].split( /=/ );
- attr[ s[ 0 ] ] = s[ 1 ];
- }
- }
-
- return attr;
-}
-
-function split_meta_hash( meta_string ) {
- var meta = meta_string.split( "" ),
- parts = [ "" ],
- in_quotes = false;
-
- while ( meta.length ) {
- var letter = meta.shift();
- switch ( letter ) {
- case " " :
- // if we're in a quoted section, keep it
- if ( in_quotes ) {
- parts[ parts.length - 1 ] += letter;
- }
- // otherwise make a new part
- else {
- parts.push( "" );
- }
- break;
- case "'" :
- case '"' :
- // reverse the quotes and move straight on
- in_quotes = !in_quotes;
- break;
- case "\\" :
- // shift off the next letter to be used straight away.
- // it was escaped so we'll keep it whatever it is
- letter = meta.shift();
- default :
- parts[ parts.length - 1 ] += letter;
- break;
- }
- }
-
- return parts;
-}
-
-/**
- * renderJsonML( jsonml[, options] ) -> String
- * - jsonml (Array): JsonML array to render to XML
- * - options (Object): options
- *
- * Converts the given JsonML into well-formed XML.
- *
- * The options currently understood are:
- *
- * - root (Boolean): wether or not the root node should be included in the
- * output, or just its children. The default `false` is to not include the
- * root itself.
- */
-expose.renderJsonML = function( jsonml, options ) {
- options = options || {};
- // include the root element in the rendered output?
- options.root = options.root || false;
- options.xhtml = options.xhtml || false;
-
- var content = [];
-
- if ( options.root ) {
- content.push( render_tree( jsonml, options.xhtml ) );
- }
- else {
- jsonml.shift(); // get rid of the tag
- if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
- jsonml.shift(); // get rid of the attributes
- }
-
- while ( jsonml.length ) {
- content.push( render_tree( jsonml.shift(), options.xhtml ) );
- }
- }
-
- return content.join( "\n\n" );
-}
-
-function render_tree( jsonml, xhtml ) {
- // basic case
- if ( typeof jsonml === "string" ) {
- return jsonml.replace( /&/g, "&" )
- .replace( //g, ">" );
- }
-
- var tag = jsonml.shift(),
- attributes = {},
- content = [];
-
- if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
- attributes = jsonml.shift();
- }
-
- while ( jsonml.length ) {
- content.push( arguments.callee( jsonml.shift(), xhtml ) );
- }
-
- var tag_attrs = "";
- for ( var a in attributes ) {
- tag_attrs += " " + a + '="' + attributes[ a ] + '"';
- }
-
- // if xhtml, self-close empty tags
- // be careful about adding whitespace here for inline elements
- var markup = "<"+ tag + tag_attrs;
- var contentstr = content.join( "" );
- if ( xhtml && contentstr.length == 0 ) {
- markup += " />";
- }
- else {
- markup += ">" + contentstr + "" + tag + ">";
- }
- return markup;
-}
-
-function convert_tree_to_html( tree, references ) {
- // shallow clone
- var jsonml = tree.slice( 0 );
-
- // Clone attributes if the exist
- var attrs = extract_attr( jsonml );
- if ( attrs ) {
- jsonml[ 1 ] = {};
- for ( var i in attrs ) {
- jsonml[ 1 ][ i ] = attrs[ i ];
- }
- attrs = jsonml[ 1 ];
- }
-
- // basic case
- if ( typeof jsonml === "string" ) {
- return jsonml;
- }
-
- // convert this node
- switch ( jsonml[ 0 ] ) {
- case "header":
- jsonml[ 0 ] = "h" + jsonml[ 1 ].level;
- delete jsonml[ 1 ].level;
- break;
- case "bulletlist":
- jsonml[ 0 ] = "ul";
- break;
- case "numberlist":
- jsonml[ 0 ] = "ol";
- break;
- case "listitem":
- jsonml[ 0 ] = "li";
- break;
- case "para":
- jsonml[ 0 ] = "p";
- break;
- case "markdown":
- jsonml[ 0 ] = "html";
- if ( attrs ) delete attrs.references;
- break;
- case "code_block":
- jsonml[ 0 ] = "pre";
- var i = attrs ? 2 : 1;
- var code = [ "code" ];
- code.push.apply( code, jsonml.splice( i ) );
- jsonml[ i ] = code;
- break;
- case "inlinecode":
- jsonml[ 0 ] = "code";
- break;
- case "img":
- jsonml[ 1 ].src = jsonml[ 1 ].href;
- delete jsonml[ 1 ].href;
- break;
- case "linebreak":
- jsonml[0] = "br";
- break;
- case "link":
- jsonml[ 0 ] = "a";
- break;
- case "link_ref":
- jsonml[ 0 ] = "a";
-
- // grab this ref and clean up the attribute node
- var ref = references[ attrs.ref ];
-
- // if the reference exists, make the link
- if ( ref ) {
- delete attrs.ref;
-
- // add in the href and title, if present
- attrs.href = ref.href;
- if ( ref.title ) {
- attrs.title = ref.title;
- }
-
- // get rid of the unneeded original text
- delete attrs.original;
- }
- // the reference doesn't exist, so revert to plain text
- else {
- return attrs.original;
- }
- break;
- }
-
- // convert all the children
- var i = 1;
-
- // deal with the attribute node, if it exists
- if ( attrs ) {
- // if there are keys, skip over it
- for ( var key in jsonml[ 1 ] ) {
- i = 2;
- }
- // if there aren't, remove it
- if ( i === 1 ) {
- jsonml.splice( i, 1 );
- }
- }
-
- for ( ; i < jsonml.length; ++i ) {
- jsonml[ i ] = arguments.callee( jsonml[ i ], references );
- }
-
- return jsonml;
-}
-
-
-// merges adjacent text nodes into a single node
-function merge_text_nodes( jsonml ) {
- // skip the tag name and attribute hash
- var i = extract_attr( jsonml ) ? 2 : 1;
-
- while ( i < jsonml.length ) {
- // if it's a string check the next item too
- if ( typeof jsonml[ i ] === "string" ) {
- if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) {
- // merge the second string into the first and remove it
- jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ];
- }
- else {
- ++i;
- }
- }
- // if it's not a string recurse
- else {
- arguments.callee( jsonml[ i ] );
- ++i;
- }
- }
-}
-
-})(exports);