1
0

loadmode.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"), "cjs");
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], function(CM) { mod(CM, "amd"); });
  8. else // Plain browser env
  9. mod(CodeMirror, "plain");
  10. })(function(CodeMirror, env) {
  11. if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
  12. var loading = {};
  13. function splitCallback(cont, n) {
  14. var countDown = n;
  15. return function() { if (--countDown == 0) cont(); };
  16. }
  17. function ensureDeps(mode, cont) {
  18. var deps = CodeMirror.modes[mode].dependencies;
  19. if (!deps) return cont();
  20. var missing = [];
  21. for (var i = 0; i < deps.length; ++i) {
  22. if (!CodeMirror.modes.hasOwnProperty(deps[i]))
  23. missing.push(deps[i]);
  24. }
  25. if (!missing.length) return cont();
  26. var split = splitCallback(cont, missing.length);
  27. for (var i = 0; i < missing.length; ++i)
  28. CodeMirror.requireMode(missing[i], split);
  29. }
  30. CodeMirror.requireMode = function(mode, cont) {
  31. if (typeof mode != "string") mode = mode.name;
  32. if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
  33. if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
  34. var file = CodeMirror.modeURL.replace(/%N/g, mode);
  35. if (env == "plain") {
  36. var script = document.createElement("script");
  37. script.src = file;
  38. var others = document.getElementsByTagName("script")[0];
  39. var list = loading[mode] = [cont];
  40. CodeMirror.on(script, "load", function() {
  41. ensureDeps(mode, function() {
  42. for (var i = 0; i < list.length; ++i) list[i]();
  43. });
  44. });
  45. others.parentNode.insertBefore(script, others);
  46. } else if (env == "cjs") {
  47. require(file);
  48. cont();
  49. } else if (env == "amd") {
  50. requirejs([file], cont);
  51. }
  52. };
  53. CodeMirror.autoLoadMode = function(instance, mode) {
  54. if (!CodeMirror.modes.hasOwnProperty(mode))
  55. CodeMirror.requireMode(mode, function() {
  56. instance.setOption("mode", instance.getOption("mode"));
  57. });
  58. };
  59. });