source-highlight 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env node
  2. // Simple command-line code highlighting tool. Reads code from stdin,
  3. // spits html to stdout. For example:
  4. //
  5. // echo 'function foo(a) { return a; }' | bin/source-highlight -s javascript
  6. // bin/source-highlight -s
  7. var fs = require("fs");
  8. var CodeMirror = require("../addon/runmode/runmode.node.js");
  9. require("../mode/meta.js");
  10. var sPos = process.argv.indexOf("-s");
  11. if (sPos == -1 || sPos == process.argv.length - 1) {
  12. console.error("Usage: source-highlight -s language");
  13. process.exit(1);
  14. }
  15. var lang = process.argv[sPos + 1].toLowerCase(), modeName = lang;
  16. CodeMirror.modeInfo.forEach(function(info) {
  17. if (info.mime == lang) {
  18. modeName = info.mode;
  19. } else if (info.name.toLowerCase() == lang) {
  20. modeName = info.mode;
  21. lang = info.mime;
  22. }
  23. });
  24. if (!CodeMirror.modes[modeName])
  25. require("../mode/" + modeName + "/" + modeName + ".js");
  26. function esc(str) {
  27. return str.replace(/[<&]/g, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
  28. }
  29. var code = fs.readFileSync("/dev/stdin", "utf8");
  30. var curStyle = null, accum = "";
  31. function flush() {
  32. if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
  33. else process.stdout.write(esc(accum));
  34. }
  35. CodeMirror.runMode(code, lang, function(text, style) {
  36. if (style != curStyle) {
  37. flush();
  38. curStyle = style; accum = text;
  39. } else {
  40. accum += text;
  41. }
  42. });
  43. flush();