forked from GitbookIO/plugin-codesnippet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (59 loc) · 2.2 KB
/
index.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
var Q = require('q');
var url = require('url');
var fs = require('fs');
var path = require('path');
var request = require('request');
function codeblock(language, content) {
var cleaned = content.replace(/</g, '<').replace(/>/g, '>');
return '<pre><code class="lang-' + language + '">' + cleaned + '</code></pre>';
}
// Convert a range to a {start,end} object
function rangeToLines(range) {
range = (range || '').split(':');
if (range.length != 2) {
return null;
}
return {
start: Number(range[0]) - 1,
end: Number(range[1])
}
}
module.exports = {
blocks: {
codesnippet: {
process: function(block) {
var that = this;
var filename = block.args[0];
// Lines range
var range = rangeToLines(block.kwargs.lines);
// Determine language
var language = block.kwargs.language || (filename? path.extname(filename).slice(1) : '');
if (!filename) return codeblock(language, block.body);
// Read the file
return Q()
.then(function() {
if (url.parse(filename).protocol) {
var d = Q.defer();
request(filename, function (error, response, body) {
if (error) return d.reject(error);
if (Math.floor(response.statusCode/200) != 1) d.reject(new Error('No 2XX status code when downloading '+filename));
d.resolve(body.toString('utf-8'));
});
return d.promise;
} else {
return that.book.readFile(filename);
}
})
// Return the html content
.then(function(content) {
if (range) {
var lines = content.split(/\r?\n/);
lines = lines.slice(range.start, range.end);
content = lines.join('\n');
}
return codeblock(language, content);
});
}
}
}
};