runmode.js 2.7 KB

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