runmode.js 1.9 KB

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