UNPKG

2.73 kBJavaScriptView Raw
1/*!
2 * WMD - Wanton Markdown
3 * Copyright (c) 2010 Caolan McMahon
4 */
5
6/**
7 * Module dependencies
8 */
9
10var fs = require('fs'),
11 preprocessors = require('./preprocessors'),
12 postprocessors = require('./postprocessors'),
13 vm = require('vm');
14
15/**
16 * Showdown isn't a commonjs module, load it manually
17 */
18
19var Showdown = (function () {
20 var sandbox = {};
21 var filename = __dirname + '/vendor/showdown/src/showdown.js';
22 var content = fs.readFileSync(filename, 'utf8');
23 vm.runInNewContext(content, sandbox);
24 return sandbox.Showdown;
25})();
26
27
28/**
29 * Main function for converting markdown to HTML.
30 *
31 * @param {String} content
32 * @param {Object} options
33 * @return {String}
34 * @api public
35 */
36
37var exports = module.exports = function (content, options) {
38 var doc = {raw: content, markdown: content};
39 var opt = exports.readOptions(options);
40 exports.preprocess(doc, opt);
41 doc.html = exports.processor(doc.markdown);
42 exports.postprocess(doc, opt);
43 doc.toString = function () {
44 return doc.html;
45 };
46 return doc;
47};
48
49
50/**
51 * Create a Showdown converter instance to use and export it
52 *
53 * @param {String} markdown
54 * @return {String}
55 * @api public
56 */
57
58exports.processor = new Showdown.converter().makeHtml;
59
60/**
61 * Export the preprocessors and postprocessors submodules for convenience
62 */
63
64exports.preprocessors = preprocessors;
65exports.postprocessors = postprocessors;
66
67/**
68 * Extends a default set of options with those passed to it.
69 *
70 * @param {Object} options
71 * @return {Object}
72 * @api public
73 */
74
75exports.readOptions = function (options) {
76 var obj = {
77 preprocessors: [
78 exports.preprocessors.metadata,
79 exports.preprocessors.underscores
80 ],
81 postprocessors: []
82 };
83 for (var k in options) {
84 obj[k] = options[k];
85 }
86 return obj;
87};
88
89/**
90 * Runs all the preprocessors defined in options on the doc object.
91 * This is executed before passing the doc's markdown property to the processor
92 * function to be turned into HTML.
93 *
94 * @param {Object} doc
95 * @param {Object} options
96 * @return {String}
97 * @api public
98 */
99
100exports.preprocess = function (doc, options) {
101 return options.preprocessors.reduce(function (doc, fn) {
102 return fn(doc);
103 }, doc);
104};
105
106/**
107 * Runs all the postprocessors defined in options on the doc object.
108 * This is executed after passing the doc's markdown property to the processor
109 * function to be turned into HTML.
110 *
111 * @param {Object} doc
112 * @param {Object} options
113 * @return {String}
114 * @api public
115 */
116
117exports.postprocess = function (doc, options) {
118 return options.postprocessors.reduce(function (doc, fn) {
119 return fn(doc);
120 }, doc);
121};