/
markdown.js
99 lines (85 loc) · 2.24 KB
/
markdown.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
const hljs = require('highlight.js');
const utils = require('handlebars-utils');
const Remarkable = require('remarkable');
/**
* Expose markdown `helpers` (for performance we're using getters so
* that the helpers are only loaded if called)
*/
var helpers = module.exports;
var markdown;
/**
* Block helper that converts a string of inline markdown to HTML.
*
* ```handlebars
* {{#markdown}}
* # Foo
* {{/markdown}}
* <!-- results in: <h1>Foo</h1> -->
* ```
* @name .markdown
* @param {Object} `context`
* @param {Object} `options`
* @return {String}
* @block
* @api public
*/
Object.defineProperty(helpers, 'markdown', {
configurable: true,
enumerable: true,
set: function(val) {
markdown = val;
},
get: function() {
// this is defined as a getter to avoid calling this function
// unless the helper is actually used
return markdown || (markdown = this.helpersForMarkdown());
}
});
/**
* Read a markdown file from the file system and inject its contents after
* converting it to HTML.
*
* ```handlebars
* {{md "foo/bar.md"}}
* ```
* @param {Object} `context`
* @param {Object} `options`
* @return {String}
* @block
* @api public
*/
helpers.md = require('helper-md');
helpers.helpersForMarkdown = function(config) {
const defaults = { html: true, breaks: true, highlight: helpers.highlightFormMarkdown };
if (typeof config === 'string' || utils.isOptions(config)) {
return markdown.apply(defaults, arguments);
}
function markdown(str, locals, options) {
if (typeof str !== 'string') {
options = locals;
locals = str;
str = true;
}
if (utils.isOptions(locals)) {
options = locals;
locals = {};
}
const ctx = utils.context(this, locals, options);
let opts = utils.options(this, locals, options);
opts = Object.assign({}, defaults, config, opts);
if (opts.hasOwnProperty('lang')) {
opts.langPrefix = opts.lang;
}
const md = new Remarkable(opts);
const val = utils.value(str, ctx, options);
return md.render(val);
}
return markdown;
};
helpers.highlightFormMarkdown = function(code, lang) {
if(lang) {
return hljs.highlight(code, {language: lang}).value;
}
return hljs.highlightAuto(code).value;
}