仰望星辰工作室

better-staridc-MNBT

better-staridc-MNBT/ imsetes/codemirror/bin/source-highlight 1.4 KB · 48 行 原始文件
Z zfhsh first commit 2 个月前
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
9var fs = require("fs");
10
11var CodeMirror = require("../addon/runmode/runmode.node.js");
12require("../mode/meta.js");
13
14var sPos = process.argv.indexOf("-s");
15if (sPos == -1 || sPos == process.argv.length - 1) {
16 console.error("Usage: source-highlight -s language");
17 process.exit(1);
18}
19var lang = process.argv[sPos + 1].toLowerCase(), modeName = lang;
20var found = CodeMirror.findModeByMIME(lang) || CodeMirror.findModeByName(lang)
21if (found) {
22 modeName = found.mode
23 lang = found.mime
24}
25
26if (!CodeMirror.modes[modeName])
27 require("../mode/" + modeName + "/" + modeName + ".js");
28
29function esc(str) {
30 return str.replace(/[<&]/g, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
31}
32
33var code = fs.readFileSync("/dev/stdin", "utf8");
34var curStyle = null, accum = "";
35function flush() {
36 if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
37 else process.stdout.write(esc(accum));
38}
39
40CodeMirror.runMode(code, lang, function(text, style) {
41 if (style != curStyle) {
42 flush();
43 curStyle = style; accum = text;
44 } else {
45 accum += text;
46 }
47});
48flush();