openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

source-highlight (1389B)


      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 var 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 var found = CodeMirror.findModeByMIME(lang) || CodeMirror.findModeByName(lang)
     21 if (found) {
     22   modeName = found.mode
     23   lang = found.mime
     24 }
     25 
     26 if (!CodeMirror.modes[modeName])
     27   require("../mode/" + modeName + "/" + modeName + ".js");
     28 
     29 function esc(str) {
     30   return str.replace(/[<&]/g, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
     31 }
     32 
     33 var code = fs.readFileSync("/dev/stdin", "utf8");
     34 var curStyle = null, accum = "";
     35 function 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 
     40 CodeMirror.runMode(code, lang, function(text, style) {
     41   if (style != curStyle) {
     42     flush();
     43     curStyle = style; accum = text;
     44   } else {
     45     accum += text;
     46   }
     47 });
     48 flush();