summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-markdown/lib/page.js
blob: 8d3e5a63e717e15b646fc159bf2ada87ba305aaa (plain)
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
var _ = require('lodash');
var kramed = require('kramed');

var annotate = require('./annotate');

var RAW_START = "{% raw %}";
var RAW_END = "{% endraw %}";

function escape(str) {
    return RAW_START + str + RAW_END;
}

// Combines annotated nodes
function combine(nodes) {
    return _.pluck(nodes, 'raw').join('');
}

function escapeCodeElement(el) {
    if(el.type == 'code') {
        el.raw = escape(el.raw);
    }
    return el;
}

function preparePage(src) {
    var lexed = annotate.blocks(src);


    var escaped = lexed
    // Escape code blocks
    .map(escapeCodeElement)
    // Escape inline code blocks
    .map(function(el) {
        // Only escape paragraphs and headings
        if(!(el.type == 'paragraph' || el.type == 'heading')) {
            return el;
        }

        // Escape inline code blocks
        var newInline = annotate.inline(el.raw).map(escapeCodeElement);

        // Change raw source code
        el.raw = combine(newInline);

        return el;
    });

    return combine(escaped);
}

function parsePage(src) {
    var options = _.extend({}, kramed.defaults);

    return {
        sections: [
            {
                type: "normal",
                content: kramed(src, options)
            }
        ]
    };
}

// Exports
module.exports = parsePage;
module.exports.prepare = preparePage;