source-highlight 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. 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. function ensureMode(name) {
  25. if (CodeMirror.modes[name] || name == "null") return;
  26. try {
  27. require("../mode/" + name + "/" + name + ".js");
  28. } catch(e) {
  29. console.error("Could not load mode " + name + ".");
  30. process.exit(1);
  31. }
  32. var obj = CodeMirror.modes[name];
  33. if (obj.dependencies) obj.dependencies.forEach(ensureMode);
  34. }
  35. ensureMode(modeName);
  36. function esc(str) {
  37. return str.replace(/[<&]/, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
  38. }
  39. var code = fs.readFileSync("/dev/stdin", "utf8");
  40. var curStyle = null, accum = "";
  41. function flush() {
  42. if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
  43. else process.stdout.write(esc(accum));
  44. }
  45. CodeMirror.runMode(code, lang, function(text, style) {
  46. if (style != curStyle) {
  47. flush();
  48. curStyle = style; accum = text;
  49. } else {
  50. accum += text;
  51. }
  52. });
  53. flush();