-
Notifications
You must be signed in to change notification settings - Fork 1
/
ansi-markdown.js
189 lines (166 loc) · 5.2 KB
/
ansi-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
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
var fs = require('fs');
var color = require('ansi-color').set;
var figlet = require('figlet');
var marked = require('marked');
var async = require('async');
var pygmentize = require('pygmentize-bundled');
var asyncReplace = require('async-replace');
var he = require('he');
var wrap = require('wordwrap').hard;
var exec = require('child_process').exec;
// Center some text on the screen
var center = function(text) {
return text.split('\n').map(function(line) {
var spaces = Math.floor((process.stdout.columns - he.decode(line).replace(/\033\[[0-9;]*m/g, '').length) / 2) + 1;
if (spaces < 0) {
throw new Error('The following is too wide to fit on screen: ' + text);
}
return (new Array(spaces)).join(' ') + line;
}).join('\n');
};
// Put some newlines around it
var wrapInNl = function(text) {
return '\n' + text + '\n';
};
var renderer = new marked.Renderer();
renderer.br = function() {
return '\n';
};
// Highlighting is handled further down.
renderer.code = function(code) {
if (code === '') {
return '';
} else {
return wrapInNl(code);
}
};
renderer.hr = function() {
return wrapInNl(color((new Array(process.stdout.columns + 1)).join('-'), 'blue') + '\n');
};
// Headers should be figleted
renderer.heading = function(text, level, raw) {
return '\n\n' + center(figlet.textSync(raw)) + '\n';
};
// Special handling for paragraphs
renderer.paragraph = function(text) {
text = wrap(process.stdout.columns)(text);
// Just a tilde means a couple of blank lines
if (text === '~') {
return '\n\n';
// Paragraphs that start with a tilde are centered
} else if (text.match(/^~/)) {
return center(text.replace(/^~\s*/, '')) + '\n';
} else {
return text + '\n\n';
}
};
// Make lists nice and dandy
renderer.list = function(text, ordered) {
if (ordered) {
text = text.split('\n').slice(0, -1).reduce(function(lines, line) {
return lines.concat(line.replace(/^\*/, (lines.length + 1) + '.'));
}, []).join('\n') + '\n';
}
return text;
};
renderer.listitem = function(text) {
return '* ' + text + '\n';
};
// Haha such a hack
renderer.image = function(href, _, alt) {
return '<REPLACEWITHIMG>' + alt + '::' + href + '</REPLACEWITHIMG>';
};
// This is horrible, horrible
function insertImages(text, callback) {
var matches = text.match(/\<REPLACEWITHIMG\>(.*?)::(.*?)\<\/REPLACEWITHIMG\>/);
if (matches) {
var width = parseInt(matches[1], 10);
var tube;
var cmd;
if (width !== NaN && width > 0) {
cmd = 'node_modules/picture-tube/bin/tube.js --cols ' + width + ' "' + matches[2] + '"';
} else {
cmd = 'node_modules/picture-tube/bin/tube.js "' + matches[2] + '"';
}
exec(cmd, function(_, data) {
var img = center(data);
text = text.replace(matches[0], img);
insertImages(text, callback);
});
} else {
callback(null, text);
}
}
// Don't put the emPHASis on the wrong sylLABle
renderer.em = function(text) {
return color(text, 'bold+yellow');
};
renderer.strong = function(text) {
return color(text, 'bold+green+italic');
};
// Hide blockquotes altogether. Use for adding comments.
renderer.blockquote = function() {
return '';
};
marked.setOptions({
renderer: renderer
});
var inlineCodeRegex = /(`+)\s*(lang=(\w+)\s+)?([\s\S]*?[^`])\s*\1(?!`)/g;
function doThePygmentsThing(code, lang, callback) {
if (lang) {
pygmentize({ lang: lang, format: '256', options: { style: 'monokai' } }, code, function(err, result) {
if (err) {
callback(color(code, 'blue'));
} else {
callback(result.toString().trim());
}
});
} else {
callback(color(code, 'blue'));
}
}
module.exports.render = function(content, callback) {
var codeToRun = [];
// We need to do some work on the lexed tokens before generating the final output
async.map(marked.lexer(content), function(token, tokenCallback) {
// Inline tokens are not exposed through the lexer, so we do highlighted code spans the hard way
if (token.type === 'paragraph' || token.type === 'text') {
if (token.text.match(inlineCodeRegex)) {
asyncReplace(token.text, inlineCodeRegex, function(_, _, _, lang, code, _, _, replaceCallback) {
doThePygmentsThing(code, lang, function(result) {
replaceCallback(null, result);
});
}, function(err, result) {
token.text = result;
tokenCallback(null, token);
});
} else {
tokenCallback(null, token);
}
} else if (token.type === 'code') {
token.escaped = true;
// Hashbanged code should be executed
if (token.lang === '#!') {
codeToRun.push(token.text);
token.text = '';
tokenCallback(null, token);
} else {
doThePygmentsThing(token.text, token.lang, function(result) {
token.text = result;
tokenCallback(null, token);
});
}
} else {
tokenCallback(null, token);
}
}, function(err, tokens) {
// This is needed for some reason
if (!tokens.links) {
tokens.links = {};
}
// Finally parse, insert images, and make sure html entities are decoded
insertImages(marked.parser(tokens), function(err, src) {
callback(he.decode(src), codeToRun);
});
});
};