You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.4 KiB

7 months ago
  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. var found = CodeMirror.findModeByMIME(lang) || CodeMirror.findModeByName(lang)
  17. if (found) {
  18. modeName = found.mode
  19. lang = found.mime
  20. }
  21. if (!CodeMirror.modes[modeName])
  22. require("../mode/" + modeName + "/" + modeName + ".js");
  23. function esc(str) {
  24. return str.replace(/[<&]/g, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
  25. }
  26. var code = fs.readFileSync("/dev/stdin", "utf8");
  27. var curStyle = null, accum = "";
  28. function flush() {
  29. if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
  30. else process.stdout.write(esc(accum));
  31. }
  32. CodeMirror.runMode(code, lang, function(text, style) {
  33. if (style != curStyle) {
  34. flush();
  35. curStyle = style; accum = text;
  36. } else {
  37. accum += text;
  38. }
  39. });
  40. flush();