1
0

loadmode.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (function() {
  2. if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
  3. var loading = {};
  4. function splitCallback(cont, n) {
  5. var countDown = n;
  6. return function() { if (--countDown == 0) cont(); };
  7. }
  8. function ensureDeps(mode, cont) {
  9. var deps = CodeMirror.modes[mode].dependencies;
  10. if (!deps) return cont();
  11. var missing = [];
  12. for (var i = 0; i < deps.length; ++i) {
  13. if (!CodeMirror.modes.hasOwnProperty(deps[i]))
  14. missing.push(deps[i]);
  15. }
  16. if (!missing.length) return cont();
  17. var split = splitCallback(cont, missing.length);
  18. for (var i = 0; i < missing.length; ++i)
  19. CodeMirror.requireMode(missing[i], split);
  20. }
  21. CodeMirror.requireMode = function(mode, cont) {
  22. if (typeof mode != "string") mode = mode.name;
  23. if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
  24. if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
  25. var script = document.createElement("script");
  26. script.src = CodeMirror.modeURL.replace(/%N/g, mode);
  27. var others = document.getElementsByTagName("script")[0];
  28. others.parentNode.insertBefore(script, others);
  29. var list = loading[mode] = [cont];
  30. var count = 0, poll = setInterval(function() {
  31. if (++count > 100) return clearInterval(poll);
  32. if (CodeMirror.modes.hasOwnProperty(mode)) {
  33. clearInterval(poll);
  34. loading[mode] = null;
  35. ensureDeps(mode, function() {
  36. for (var i = 0; i < list.length; ++i) list[i]();
  37. });
  38. }
  39. }, 200);
  40. };
  41. CodeMirror.autoLoadMode = function(instance, mode) {
  42. if (!CodeMirror.modes.hasOwnProperty(mode))
  43. CodeMirror.requireMode(mode, function() {
  44. instance.setOption("mode", instance.getOption("mode"));
  45. });
  46. };
  47. }());