UNPKG

1.46 kBJavaScriptView Raw
1'use strict';
2
3var xtend = require('xtend');
4var matters = require('./lib/matters');
5var parse = require('./lib/parse');
6var compile = require('./lib/compile');
7
8module.exports = frontmatter;
9
10function frontmatter(options) {
11 var parser = this.Parser;
12 var compiler = this.Compiler;
13 var config = matters(options || ['yaml']);
14
15 if (isRemarkParser(parser)) {
16 attachParser(parser, config);
17 }
18
19 if (isRemarkCompiler(compiler)) {
20 attachCompiler(compiler, config);
21 }
22}
23
24function attachParser(parser, matters) {
25 var proto = parser.prototype;
26 var tokenizers = wrap(parse, matters);
27 var names = [];
28 var key;
29
30 for (key in tokenizers) {
31 names.push(key);
32 }
33
34 proto.blockMethods = names.concat(proto.blockMethods);
35 proto.blockTokenizers = xtend(tokenizers, proto.blockTokenizers);
36}
37
38function attachCompiler(compiler, matters) {
39 var proto = compiler.prototype;
40 proto.visitors = xtend(wrap(compile, matters), proto.visitors);
41}
42
43function wrap(func, matters) {
44 var result = {};
45 var length = matters.length;
46 var index = -1;
47 var tuple;
48
49 while (++index < length) {
50 tuple = func(matters[index]);
51 result[tuple[0]] = tuple[1];
52 }
53
54 return result;
55}
56
57function isRemarkParser(parser) {
58 return Boolean(
59 parser &&
60 parser.prototype &&
61 parser.prototype.blockTokenizers
62 );
63}
64
65function isRemarkCompiler(compiler) {
66 return Boolean(
67 compiler &&
68 compiler.prototype &&
69 compiler.prototype.visitors
70 );
71}