runmode.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. (function(mod) {
  2. if (typeof exports == "object" && typeof module == "object") // CommonJS
  3. mod(require("../../lib/codemirror"));
  4. else if (typeof define == "function" && define.amd) // AMD
  5. define(["../../lib/codemirror"], mod);
  6. else // Plain browser env
  7. mod(CodeMirror);
  8. })(function(CodeMirror) {
  9. "use strict";
  10. CodeMirror.runMode = function(string, modespec, callback, options) {
  11. var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
  12. var ie = /MSIE \d/.test(navigator.userAgent);
  13. var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
  14. if (callback.nodeType == 1) {
  15. var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
  16. var node = callback, col = 0;
  17. node.innerHTML = "";
  18. callback = function(text, style) {
  19. if (text == "\n") {
  20. // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
  21. // Emitting a carriage return makes everything ok.
  22. node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
  23. col = 0;
  24. return;
  25. }
  26. var content = "";
  27. // replace tabs
  28. for (var pos = 0;;) {
  29. var idx = text.indexOf("\t", pos);
  30. if (idx == -1) {
  31. content += text.slice(pos);
  32. col += text.length - pos;
  33. break;
  34. } else {
  35. col += idx - pos;
  36. content += text.slice(pos, idx);
  37. var size = tabSize - col % tabSize;
  38. col += size;
  39. for (var i = 0; i < size; ++i) content += " ";
  40. pos = idx + 1;
  41. }
  42. }
  43. if (style) {
  44. var sp = node.appendChild(document.createElement("span"));
  45. sp.className = "cm-" + style.replace(/ +/g, " cm-");
  46. sp.appendChild(document.createTextNode(content));
  47. } else {
  48. node.appendChild(document.createTextNode(content));
  49. }
  50. };
  51. }
  52. var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
  53. for (var i = 0, e = lines.length; i < e; ++i) {
  54. if (i) callback("\n");
  55. var stream = new CodeMirror.StringStream(lines[i]);
  56. while (!stream.eol()) {
  57. var style = mode.token(stream, state);
  58. callback(stream.current(), style, i, stream.start, state);
  59. stream.start = stream.pos;
  60. }
  61. }
  62. };
  63. });