2
0

runmode.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. CodeMirror.runMode = function(string, modespec, callback, options) {
  2. var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
  3. if (callback.nodeType == 1) {
  4. var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
  5. var node = callback, col = 0;
  6. node.innerHTML = "";
  7. callback = function(text, style) {
  8. if (text == "\n") {
  9. node.appendChild(document.createElement("br"));
  10. col = 0;
  11. return;
  12. }
  13. var content = "";
  14. // replace tabs
  15. for (var pos = 0;;) {
  16. var idx = text.indexOf("\t", pos);
  17. if (idx == -1) {
  18. content += text.slice(pos);
  19. col += text.length - pos;
  20. break;
  21. } else {
  22. col += idx - pos;
  23. content += text.slice(pos, idx);
  24. var size = tabSize - col % tabSize;
  25. col += size;
  26. for (var i = 0; i < size; ++i) content += " ";
  27. pos = idx + 1;
  28. }
  29. }
  30. if (style) {
  31. var sp = node.appendChild(document.createElement("span"));
  32. sp.className = "cm-" + style.replace(/ +/g, " cm-");
  33. sp.appendChild(document.createTextNode(content));
  34. } else {
  35. node.appendChild(document.createTextNode(content));
  36. }
  37. };
  38. }
  39. var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
  40. for (var i = 0, e = lines.length; i < e; ++i) {
  41. if (i) callback("\n");
  42. var stream = new CodeMirror.StringStream(lines[i]);
  43. while (!stream.eol()) {
  44. var style = mode.token(stream, state);
  45. callback(stream.current(), style, i, stream.start);
  46. stream.start = stream.pos;
  47. }
  48. }
  49. };