Fix: merge conflict
[myslice.git] / to-be-integrated / third-party / codemirror-3.15 / bin / source-highlight
1 #!/usr/bin/env node
2
3 // Simple command-line code highlighting tool. Reads code from stdin,
4 // spits html to stdout. For example:
5 //
6 //   echo 'function foo(a) { return a; }' | bin/source-highlight -s javascript
7 //   bin/source-highlight -s 
8
9 var fs = require("fs");
10
11 CodeMirror = require("../addon/runmode/runmode.node.js");
12 require("../mode/meta.js");
13
14 var sPos = process.argv.indexOf("-s");
15 if (sPos == -1 || sPos == process.argv.length - 1) {
16    console.error("Usage: source-highlight -s language");
17    process.exit(1);
18 }
19 var lang = process.argv[sPos + 1].toLowerCase(), modeName = lang;
20 CodeMirror.modeInfo.forEach(function(info) {
21   if (info.mime == lang) {
22     modeName = info.mode;
23   } else if (info.name.toLowerCase() == lang) {
24     modeName = info.mode;
25     lang = info.mime;
26   }
27 });
28
29 function ensureMode(name) {
30   if (CodeMirror.modes[name] || name == "null") return;
31   try {
32     require("../mode/" + name + "/" + name + ".js");
33   } catch(e) {
34     console.error("Could not load mode " + name + ".");
35     process.exit(1);
36   }
37   var obj = CodeMirror.modes[name];
38   if (obj.dependencies) obj.dependencies.forEach(ensureMode);
39 }
40 ensureMode(modeName);
41
42 function esc(str) {
43   return str.replace(/[<&]/, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
44 }
45
46 var code = fs.readFileSync("/dev/stdin", "utf8");
47 var curStyle = null, accum = "";
48 function flush() {
49   if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
50   else process.stdout.write(esc(accum));
51 }
52
53 CodeMirror.runMode(code, lang, function(text, style) {
54   if (style != curStyle) {
55     flush();
56     curStyle = style; accum = text;
57   } else {
58     accum += text;
59   }
60 });
61 flush();