summaryrefslogtreecommitdiff
path: root/lib/writers/markdown-writer.js
blob: ff2d4b4c8a45c7ef119ecdbed897805a5d1870e6 (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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
var _ = require("underscore");


function markdownElement(start, end) {
    if (end === undefined) {
        end = start;
    }

    this.open = function(attrs) {
        return start;
    };

    this.close = function() {
        return end;
    };
}

function markdownLink() {
    var href;

    this.open = function(attributes) {
        href = attributes.href;
        return "[";
    };

    this.close = function() {
        return "](" + (href || "") + ")";
    };
    
    this.anchorPosition = "before";
}

function markdownImage() {
    this.open = function(attributes) {
        var src = attributes.src || "";
        var altText = attributes.alt || "";
        if (src || altText) {
            return "![" + altText + "](" + src + ")";
        }
    };

    this.close = function() {
        return "";
    };
}

function markdownList() {
    this.open = function(attrs) {
        return attrs.indent > -1 ? "\n" : "";
    };

    this.close = function(attrs) {
        return attrs.indent > -1 ? "" : "\n";
    };
}

function markdownListItem() {
    this.open = function(attrs) {
        var output = "";

        for(var i = 0; i < attrs.indent; ++i) {
            output += "\t";
        }

        return output + (attrs.type === "ul" ? "-" : attrs.count + ".") + " ";
    };

    this.close = function() {
        return "\n";
    };
}

// map HTML tags to Markdown syntax
var htmlmarkdown = {
    // paragraphs elements use three line feeds to close
    // this prevents them being caught by collapsing list elements in `asString`
    // while still allowing them to be collapsed when multiple empty lines are removed
    "p": new markdownElement("", "\n\n\n"),
    "br": new markdownElement("", "  \n"),
    "ul": new markdownList(),
    "ol": new markdownList(),
    "li": new markdownListItem(),
    "strong": new markdownElement("**"),
    "em": new markdownElement("*"),
    "a": new markdownLink(),
    "img": new markdownImage(),
};

(function() {
    for (var i = 1; i <= 6; i++) {
        htmlmarkdown["h" + i] = new markdownElement(repeatString("#", i) + " ", "\n\n\n");
    }
})();

function repeatString(value, count) {
    return new Array(count + 1).join(value);
}

function markdownWriter() {
    var fragments = [];
    var listStack = [];
    var list = {
        indent: -1,
        type: "ul",
        count: 0
    };
    
    function isList(tagName) {
        return tagName === "ul" || tagName === "ol";
    }

    function open(tagName, attributes) {
        attributes = attributes || {};
        
        var idHasBeenWritten = false;
        
        if (htmlmarkdown[tagName]) {
            if (htmlmarkdown[tagName].anchorPosition === "before") {
                writeAnchor(attributes);
                idHasBeenWritten = true;
            }
            
            if (tagName === "li") {
                attributes.indent = list.indent;
                attributes.type = list.type;
                attributes.count = ++list.count;
            } else if (isList(tagName)) {
                attributes.indent = list.indent;
            }

            fragments.push(htmlmarkdown[tagName].open(attributes));

            if (isList(tagName)) {
                listStack.push(_.clone(list));

                list.type = tagName;
                list.indent++;
                list.count = 0;
            }
        }
        if (!idHasBeenWritten) {
            writeAnchor(attributes);
        }
    }
    
    function writeAnchor(attributes) {
        if (attributes.id) {
            fragments.push('<a id="' + attributes.id + '"></a>');
        }
    }
    
    function close(tagName) {
        if (htmlmarkdown[tagName]) {
            if (isList(tagName)) {
                list = listStack.pop();
            }

            fragments.push(htmlmarkdown[tagName].close(list));
        }
    }
    
    function selfClosing(tagName, attributes) {
        open(tagName, attributes);
        close(tagName);
    }
    
    function text(value) {
        fragments.push(escapeMarkdown(value));
    }
    
    function append(html) {
        fragments.push(html);
    }
    
    function asString() {
        // massage the output to collapse mulitple empty lines and empty lines between nested lists
        return fragments.join("").replace(/\n{2}(\t*)([2-9]\d*\.|- )/g, "\n$1$2").replace(/\n{3,}/g, "\n\n");
    }

    return {
        asString: asString,
        open: open,
        close: close,
        text: text,
        selfClosing: selfClosing,
        append: append
    };
}

exports.writer = markdownWriter;

function escapeMarkdown(value) {
    return value
        .replace(/\\/g, '\\\\')
        .replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g, '\\$1');
}