page_engine 0.0.3 → 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. data/app/assets/javascripts/page_engine.js +53 -50
  2. data/app/assets/stylesheets/page_engine.css +2 -0
  3. data/app/controllers/admin/pages_controller.rb +1 -3
  4. data/app/helpers/pages_helper.rb +64 -71
  5. data/app/models/page.rb +6 -18
  6. data/app/views/admin/pages/_form.html.haml +3 -3
  7. data/app/views/admin/pages/_page_part_fields.html.haml +1 -1
  8. data/app/views/admin/pages/duplicate.js.erb +0 -4
  9. data/app/views/admin/pages/index.html.haml +1 -1
  10. data/app/views/pages/_nav_item.html.haml +1 -1
  11. data/lib/generators/page_engine/install/install_generator.rb +64 -0
  12. data/lib/page_engine/extensions.rb +12 -8
  13. data/lib/page_engine/instance_methods.rb +6 -6
  14. data/lib/page_engine.rb +31 -0
  15. data/spec/dummy/app/assets/stylesheets/application.css +250 -0
  16. data/spec/dummy/app/controllers/application_controller.rb +1 -1
  17. data/spec/dummy/app/views/layouts/application.html.haml +5 -3
  18. data/spec/dummy/config/initializers/page_engine.rb +13 -0
  19. data/spec/dummy/db/development.sqlite3 +0 -0
  20. data/spec/dummy/log/development.log +18618 -0
  21. data/spec/dummy/tmp/cache/assets/BF5/7E0/sprockets%2F1681222188324d465309541f4e71f6e8 +0 -0
  22. data/spec/dummy/tmp/cache/assets/C1F/4A0/sprockets%2Fb257125f39b2a708d678262f26152408 +0 -0
  23. data/spec/dummy/tmp/cache/assets/C38/BB0/sprockets%2F122300de3f3142028abb055394919a47 +0 -0
  24. data/spec/dummy/tmp/cache/assets/C51/920/sprockets%2F3522c83d77303240c3548fdd7d186194 +0 -0
  25. data/spec/dummy/tmp/cache/assets/C54/B60/sprockets%2F08007599d13c8b8205959be4709d103d +0 -0
  26. data/spec/dummy/tmp/cache/assets/C83/E20/sprockets%2F2d6f03d170965f27d7626502373e8cd2 +0 -0
  27. data/spec/dummy/tmp/cache/assets/C8E/6D0/sprockets%2F10a754e99f089474b072c71eeb960954 +0 -0
  28. data/spec/dummy/tmp/cache/assets/CAD/1B0/sprockets%2F12cb3832e2e7e34236067e9e350b8c73 +0 -0
  29. data/spec/dummy/tmp/cache/assets/CB8/880/sprockets%2F3b651a5763758db2fc0347488e69a3e1 +0 -0
  30. data/spec/dummy/tmp/cache/assets/CBA/0A0/sprockets%2F2983f7dd6130a7c24892da333c18d779 +0 -0
  31. data/spec/dummy/tmp/cache/assets/CD0/CA0/sprockets%2F719e10ea5f5b1c20b6518a1d3432774e +0 -0
  32. data/spec/dummy/tmp/cache/assets/CD1/EB0/sprockets%2Fba17700b36ee975c05d06042a6af9631 +0 -0
  33. data/spec/dummy/tmp/cache/assets/CD5/8B0/sprockets%2F31178c43077cb48bfc81217ad0872cd1 +0 -0
  34. data/spec/dummy/tmp/cache/assets/CDA/A30/sprockets%2Fd1a7692303d59c495dd61cd1d41246b5 +0 -0
  35. data/spec/dummy/tmp/cache/assets/CDD/D20/sprockets%2F070d2bf7a81574ee0e560e174737a17f +0 -0
  36. data/spec/dummy/tmp/cache/assets/CE0/CD0/sprockets%2Fd206c4ec51748382823dee1e7f28055a +0 -0
  37. data/spec/dummy/tmp/cache/assets/CE3/690/sprockets%2F9531c78d64b8651a60dd128573bbe7e1 +0 -0
  38. data/spec/dummy/tmp/cache/assets/CE3/C10/sprockets%2F05a63f093f971cd73662695fab452b0f +0 -0
  39. data/spec/dummy/tmp/cache/assets/CE7/770/sprockets%2F56570f527d86457c48485cedb2d1c30c +0 -0
  40. data/spec/dummy/tmp/cache/assets/CEE/2B0/sprockets%2F75f58ee42279991f91ac43260b9b0fe3 +0 -0
  41. data/spec/dummy/tmp/cache/assets/CF2/E60/sprockets%2F6cf94481464e607960899cc38adac2b6 +0 -0
  42. data/spec/dummy/tmp/cache/assets/D09/2D0/sprockets%2F731ea2f82a086d10ff127d30c994f53b +0 -0
  43. data/spec/dummy/tmp/cache/assets/D0D/000/sprockets%2Fbb689a9183e1482be8c02ab4f536083b +0 -0
  44. data/spec/dummy/tmp/cache/assets/D13/FF0/sprockets%2Fd62e2814c718d1a22c84c7b3a78eb948 +0 -0
  45. data/spec/dummy/tmp/cache/assets/D16/BA0/sprockets%2F141f6d67a3871387dc3a1a9963de0de7 +0 -0
  46. data/spec/dummy/tmp/cache/assets/D17/DD0/sprockets%2F04f75f0ecb38c984675d23a9144d2be7 +0 -0
  47. data/spec/dummy/tmp/cache/assets/D1A/140/sprockets%2Fe5dbcc46887452182b85e8da04994ea0 +0 -0
  48. data/spec/dummy/tmp/cache/assets/D1F/620/sprockets%2F5eb71efe5276c4b5c148cd75958e2760 +0 -0
  49. data/spec/dummy/tmp/cache/assets/D23/570/sprockets%2Fb79b2bd85b952ef68724f54e3344dd66 +0 -0
  50. data/spec/dummy/tmp/cache/assets/D26/4D0/sprockets%2Faa9fd545084f66b324662ca8f48c88f9 +0 -0
  51. data/spec/dummy/tmp/cache/assets/D27/2F0/sprockets%2F6b6e52b5006574d3fef8d34ef639978d +0 -0
  52. data/spec/dummy/tmp/cache/assets/D30/ED0/sprockets%2Fea74cc14e1532ac70f928d8d205c5a13 +0 -0
  53. data/spec/dummy/tmp/cache/assets/D32/A10/sprockets%2F13fe41fee1fe35b49d145bcc06610705 +0 -0
  54. data/spec/dummy/tmp/cache/assets/D33/E40/sprockets%2F06b596c4052fc9ad352a54ac0871cf2c +0 -0
  55. data/spec/dummy/tmp/cache/assets/D3B/4D0/sprockets%2Faf8a08611a00ade8c7f16d626708eb67 +0 -0
  56. data/spec/dummy/tmp/cache/assets/D3E/740/sprockets%2F62194496bd7f322f3b2f6f2bf602e1fb +0 -0
  57. data/spec/dummy/tmp/cache/assets/D3F/170/sprockets%2F13df698b0cd7e1f7045913a1c6a96cc4 +0 -0
  58. data/spec/dummy/tmp/cache/assets/D3F/7C0/sprockets%2F42286191d1dec5e46ae8f89a0af0d147 +0 -0
  59. data/spec/dummy/tmp/cache/assets/D40/720/sprockets%2Fe798537f2ae8abbbac509070c9e06506 +0 -0
  60. data/spec/dummy/tmp/cache/assets/D45/CF0/sprockets%2F577ac52ab81ab676640dda59969cce32 +0 -0
  61. data/spec/dummy/tmp/cache/assets/D47/1D0/sprockets%2F904ef275b101c77ee529b4fe7cf323f7 +0 -0
  62. data/spec/dummy/tmp/cache/assets/D4A/D90/sprockets%2F4f476e9f41ff71e1045d03fc36de6c66 +0 -0
  63. data/spec/dummy/tmp/cache/assets/D4C/EE0/sprockets%2F7ee487bf0d625668f3fcb075c89a420d +0 -0
  64. data/spec/dummy/tmp/cache/assets/D54/ED0/sprockets%2F71c9fa01091d432b131da3bb73faf3d4 +0 -0
  65. data/spec/dummy/tmp/cache/assets/D60/DB0/sprockets%2Fb2b29acaab38e7049fd950a381e05f11 +0 -0
  66. data/spec/dummy/tmp/cache/assets/D68/450/sprockets%2F7290abaa3947f361fb72cb333692beaf +0 -0
  67. data/spec/dummy/tmp/cache/assets/D69/910/sprockets%2F05abeb33740bac77bef60b5445695c8c +0 -0
  68. data/spec/dummy/tmp/cache/assets/D6B/230/sprockets%2F744429c3ae6d8aadf46550ee21cc58b1 +0 -0
  69. data/spec/dummy/tmp/cache/assets/D6C/7E0/sprockets%2Fd3abe581052fc2ffd33b9f465b477b14 +0 -0
  70. data/spec/dummy/tmp/cache/assets/D70/280/sprockets%2F99a543e2b6be1d37c3ccc8a90261f87a +0 -0
  71. data/spec/dummy/tmp/cache/assets/D70/330/sprockets%2F292913c88244b67cdb46da1eed327fda +0 -0
  72. data/spec/dummy/tmp/cache/assets/D71/520/sprockets%2F018fdf705225eaa53bc9c287ebd68c91 +0 -0
  73. data/spec/dummy/tmp/cache/assets/D71/5D0/sprockets%2Fc8e0dae5e23b4b3941152e3b87e7f7c6 +0 -0
  74. data/spec/dummy/tmp/cache/assets/D73/830/sprockets%2F38d93d829b7d163c372f3acd557c2eab +0 -0
  75. data/spec/dummy/tmp/cache/assets/D74/120/sprockets%2Ffbe442bef82371edd6525fe5622de319 +0 -0
  76. data/spec/dummy/tmp/cache/assets/D77/7C0/sprockets%2Fcf660249e6eb81370e70cfe24d771dfe +0 -0
  77. data/spec/dummy/tmp/cache/assets/D7C/660/sprockets%2Fbb4ce966494c0b544c7ea5f4e9c2b866 +0 -0
  78. data/spec/dummy/tmp/cache/assets/D84/210/sprockets%2Fabd0103ccec2b428ac62c94e4c40b384 +0 -0
  79. data/spec/dummy/tmp/cache/assets/D87/FA0/sprockets%2Fed7ffae98375a3c9819ee641f00e388d +0 -0
  80. data/spec/dummy/tmp/cache/assets/D92/E50/sprockets%2F09a8ce459d99efe497507cad2ed88f56 +0 -0
  81. data/spec/dummy/tmp/cache/assets/D93/670/sprockets%2Fdf4cd8447459d7b31b077d0af7aba00b +0 -0
  82. data/spec/dummy/tmp/cache/assets/D94/0C0/sprockets%2Fac68f40dcce2850b0fdd7dfb91505115 +0 -0
  83. data/spec/dummy/tmp/cache/assets/D96/AE0/sprockets%2F6c450fd116d891f54a32bcfcbd4b762b +0 -0
  84. data/spec/dummy/tmp/cache/assets/DA2/0E0/sprockets%2F71a404ff712a059b23edee96c9bfcd75 +0 -0
  85. data/spec/dummy/tmp/cache/assets/DA6/860/sprockets%2Ff5526cc6647cdd14b05aed999377abbc +0 -0
  86. data/spec/dummy/tmp/cache/assets/DA7/5F0/sprockets%2Fe92688bcadd7fcddd86227c04b9712e1 +0 -0
  87. data/spec/dummy/tmp/cache/assets/DA7/6A0/sprockets%2Fa6745bdd80053c25a9ee2d81e96adef9 +0 -0
  88. data/spec/dummy/tmp/cache/assets/DA9/890/sprockets%2Fd1501c9a42bbc34f0cc11eae60b2e22e +0 -0
  89. data/spec/dummy/tmp/cache/assets/DB7/5A0/sprockets%2Fd2fac77222901b5da4abcf1c225d91db +0 -0
  90. data/spec/dummy/tmp/cache/assets/DBE/A90/sprockets%2F40e8db6da00eac4d36841aa33ff46fb3 +0 -0
  91. data/spec/dummy/tmp/cache/assets/DC6/E60/sprockets%2F415f6a64519b7c8ae296dbbafeb105ba +0 -0
  92. data/spec/dummy/tmp/cache/assets/DC8/660/sprockets%2Fbafd7b9ed0b0c06ed5e283463ad4c547 +0 -0
  93. data/spec/dummy/tmp/cache/assets/DCA/BB0/sprockets%2F1a792cae50966aef0d0d4131fe5fafd9 +0 -0
  94. data/spec/dummy/tmp/cache/assets/DD0/D40/sprockets%2Fc5ad6e6949709508d0dbdb0b1a7ecbe9 +0 -0
  95. data/spec/dummy/tmp/cache/assets/DD9/E90/sprockets%2Fd44526e0ec17dcbbccf7e14db768e869 +0 -0
  96. data/spec/dummy/tmp/cache/assets/DDC/270/sprockets%2Fadb8f369db4f8784c76fd2ee1d3633ac +0 -0
  97. data/spec/dummy/tmp/cache/assets/DDE/420/sprockets%2F69cf180e779eb3095cebe85edbfc22b7 +0 -0
  98. data/spec/dummy/tmp/cache/assets/DE0/250/sprockets%2F1559ff83d17dd6b788d6ab7fada65ee1 +0 -0
  99. data/spec/dummy/tmp/cache/assets/DE1/B40/sprockets%2F9c7deec5e90b5957c6d5b31ded7fe074 +0 -0
  100. data/spec/dummy/tmp/cache/assets/DFB/2A0/sprockets%2F801140d7903bfebe6accecc7fc9f71e2 +0 -0
  101. data/spec/dummy/tmp/cache/assets/E01/830/sprockets%2F3359db498c5ca08b6ff0a5fe54c8acda +0 -0
  102. data/spec/dummy/tmp/cache/assets/E04/7E0/sprockets%2Fee9c0f735fc2fed82f00e66fa71bc91d +0 -0
  103. data/spec/dummy/tmp/cache/assets/E04/890/sprockets%2F2f5173deea6c795b8fdde723bb4b63af +0 -0
  104. data/spec/dummy/tmp/cache/assets/E32/C40/sprockets%2Faade2bb8a94be3f057fe7d4a6fd65a84 +0 -0
  105. data/spec/dummy/tmp/cache/assets/E51/940/sprockets%2F5c78b0ffb0472ccdce1fea8dad2142bf +0 -0
  106. data/spec/dummy/tmp/cache/assets/E70/2B0/sprockets%2F7eedcfada8bf8bff28c96d9ea93521d3 +0 -0
  107. data/spec/dummy/tmp/pids/server.pid +1 -0
  108. data/vendor/assets/javascripts/codemirror/codemirror.js +2164 -0
  109. data/vendor/assets/javascripts/codemirror/modes/css.js +124 -0
  110. data/vendor/assets/javascripts/codemirror/modes/javascript.js +348 -0
  111. data/vendor/assets/javascripts/codemirror/overlay.js +51 -0
  112. data/vendor/assets/javascripts/codemirror/runmode.js +27 -0
  113. data/vendor/assets/stylesheets/codemirror/codemirror.css +68 -0
  114. data/vendor/assets/stylesheets/codemirror/themes/cobalt.css +17 -0
  115. data/vendor/assets/stylesheets/codemirror/themes/default.css +19 -0
  116. data/vendor/assets/stylesheets/codemirror/themes/elegant.css +9 -0
  117. data/vendor/assets/stylesheets/codemirror/themes/neat.css +8 -0
  118. data/vendor/assets/stylesheets/codemirror/themes/night.css +20 -0
  119. metadata +194 -18
  120. data/lib/generators/page_engine/page_engine_generator.rb +0 -60
@@ -0,0 +1,2164 @@
1
+ // All functions that need access to the editor's state live inside
2
+ // the CodeMirror function. Below that, at the bottom of the file,
3
+ // some utilities are defined.
4
+
5
+ // CodeMirror is the only global var we claim
6
+ var CodeMirror = (function() {
7
+ // This is the function that produces an editor instance. It's
8
+ // closure is used to store the editor state.
9
+ function CodeMirror(place, givenOptions) {
10
+ // Determine effective options based on given values and defaults.
11
+ var options = {}, defaults = CodeMirror.defaults;
12
+ for (var opt in defaults)
13
+ if (defaults.hasOwnProperty(opt))
14
+ options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15
+
16
+ var targetDocument = options["document"];
17
+ // The element in which the editor lives.
18
+ var wrapper = targetDocument.createElement("div");
19
+ wrapper.className = "CodeMirror";
20
+ // This mess creates the base DOM structure for the editor.
21
+ wrapper.innerHTML =
22
+ '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea
23
+ '<textarea style="position: absolute; width: 2px;" wrap="off"></textarea></div>' +
24
+ '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' +
25
+ '<div style="position: relative">' + // Set to the height of the text, causes scrolling
26
+ '<div style="position: absolute; height: 0; width: 0; overflow: hidden;"></div>' +
27
+ '<div style="position: relative">' + // Moved around its parent to cover visible view
28
+ '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
29
+ // Provides positioning relative to (visible) text origin
30
+ '<div class="CodeMirror-lines"><div style="position: relative">' +
31
+ '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
32
+ '<div></div>' + // This DIV contains the actual code
33
+ '</div></div></div></div></div>';
34
+ if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
35
+ // I've never seen more elegant code in my life.
36
+ var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
37
+ scroller = wrapper.lastChild, code = scroller.firstChild,
38
+ measure = code.firstChild, mover = measure.nextSibling,
39
+ gutter = mover.firstChild, gutterText = gutter.firstChild,
40
+ lineSpace = gutter.nextSibling.firstChild,
41
+ cursor = lineSpace.firstChild, lineDiv = cursor.nextSibling;
42
+ if (options.tabindex != null) input.tabindex = options.tabindex;
43
+ if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
44
+
45
+ // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
46
+ var poll = new Delayed(), highlight = new Delayed(), blinker;
47
+
48
+ // mode holds a mode API object. lines an array of Line objects
49
+ // (see Line constructor), work an array of lines that should be
50
+ // parsed, and history the undo history (instance of History
51
+ // constructor).
52
+ var mode, lines = [new Line("")], work, history = new History(), focused;
53
+ loadMode();
54
+ // The selection. These are always maintained to point at valid
55
+ // positions. Inverted is used to remember that the user is
56
+ // selecting bottom-to-top.
57
+ var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
58
+ // Selection-related flags. shiftSelecting obviously tracks
59
+ // whether the user is holding shift. reducedSelection is a hack
60
+ // to get around the fact that we can't create inverted
61
+ // selections. See below.
62
+ var shiftSelecting, reducedSelection, lastDoubleClick;
63
+ // Variables used by startOperation/endOperation to track what
64
+ // happened during the operation.
65
+ var updateInput, changes, textChanged, selectionChanged, leaveInputAlone;
66
+ // Current visible range (may be bigger than the view window).
67
+ var showingFrom = 0, showingTo = 0, lastHeight = 0, curKeyId = null;
68
+ // editing will hold an object describing the things we put in the
69
+ // textarea, to help figure out whether something changed.
70
+ // bracketHighlighted is used to remember that a backet has been
71
+ // marked.
72
+ var editing, bracketHighlighted;
73
+ // Tracks the maximum line length so that the horizontal scrollbar
74
+ // can be kept static when scrolling.
75
+ var maxLine = "", maxWidth;
76
+
77
+ // Initialize the content.
78
+ operation(function(){setValue(options.value || ""); updateInput = false;})();
79
+
80
+ // Register our event handlers.
81
+ connect(scroller, "mousedown", operation(onMouseDown));
82
+ // Gecko browsers fire contextmenu *after* opening the menu, at
83
+ // which point we can't mess with it anymore. Context menu is
84
+ // handled in onMouseDown for Gecko.
85
+ if (!gecko) connect(scroller, "contextmenu", onContextMenu);
86
+ connect(code, "dblclick", operation(onDblClick));
87
+ connect(scroller, "scroll", function() {
88
+ updateDisplay([]);
89
+ if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
90
+ if (options.onScroll) options.onScroll(instance);
91
+ });
92
+ connect(window, "resize", function() {updateDisplay(true);});
93
+ connect(input, "keyup", operation(onKeyUp));
94
+ connect(input, "keydown", operation(onKeyDown));
95
+ connect(input, "keypress", operation(onKeyPress));
96
+ connect(input, "focus", onFocus);
97
+ connect(input, "blur", onBlur);
98
+
99
+ connect(scroller, "dragenter", e_stop);
100
+ connect(scroller, "dragover", e_stop);
101
+ connect(scroller, "drop", operation(onDrop));
102
+ connect(scroller, "paste", function(){focusInput(); fastPoll();});
103
+ connect(input, "paste", function(){fastPoll();});
104
+ connect(input, "cut", function(){fastPoll();});
105
+
106
+ // IE throws unspecified error in certain cases, when
107
+ // trying to access activeElement before onload
108
+ var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
109
+ if (hasFocus) setTimeout(onFocus, 20);
110
+ else onBlur();
111
+
112
+ function isLine(l) {return l >= 0 && l < lines.length;}
113
+ // The instance object that we'll return. Mostly calls out to
114
+ // local functions in the CodeMirror function. Some do some extra
115
+ // range checking and/or clipping. operation is used to wrap the
116
+ // call so that changes it makes are tracked, and the display is
117
+ // updated afterwards.
118
+ var instance = {
119
+ getValue: getValue,
120
+ setValue: operation(setValue),
121
+ getSelection: getSelection,
122
+ replaceSelection: operation(replaceSelection),
123
+ focus: function(){focusInput(); onFocus(); fastPoll();},
124
+ setOption: function(option, value) {
125
+ options[option] = value;
126
+ if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber") gutterChanged();
127
+ else if (option == "mode" || option == "indentUnit") loadMode();
128
+ else if (option == "readOnly" && value == "nocursor") input.blur();
129
+ else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value);
130
+ },
131
+ getOption: function(option) {return options[option];},
132
+ undo: operation(undo),
133
+ redo: operation(redo),
134
+ indentLine: operation(function(n, dir) {
135
+ if (isLine(n)) indentLine(n, dir == null ? "smart" : dir ? "add" : "subtract");
136
+ }),
137
+ historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
138
+ matchBrackets: operation(function(){matchBrackets(true);}),
139
+ getTokenAt: function(pos) {
140
+ pos = clipPos(pos);
141
+ return lines[pos.line].getTokenAt(mode, getStateBefore(pos.line), pos.ch);
142
+ },
143
+ getStateAfter: function(line) {
144
+ line = clipLine(line == null ? lines.length - 1: line);
145
+ return getStateBefore(line + 1);
146
+ },
147
+ cursorCoords: function(start){
148
+ if (start == null) start = sel.inverted;
149
+ return pageCoords(start ? sel.from : sel.to);
150
+ },
151
+ charCoords: function(pos){return pageCoords(clipPos(pos));},
152
+ coordsChar: function(coords) {
153
+ var off = eltOffset(lineSpace);
154
+ var line = clipLine(Math.min(lines.length - 1, showingFrom + Math.floor((coords.y - off.top) / lineHeight())));
155
+ return clipPos({line: line, ch: charFromX(clipLine(line), coords.x - off.left)});
156
+ },
157
+ getSearchCursor: function(query, pos, caseFold) {return new SearchCursor(query, pos, caseFold);},
158
+ markText: operation(function(a, b, c){return operation(markText(a, b, c));}),
159
+ setMarker: addGutterMarker,
160
+ clearMarker: removeGutterMarker,
161
+ setLineClass: operation(setLineClass),
162
+ lineInfo: lineInfo,
163
+ addWidget: function(pos, node, scroll, where) {
164
+ pos = localCoords(clipPos(pos));
165
+ var top = pos.yBot, left = pos.x;
166
+ node.style.position = "absolute";
167
+ code.appendChild(node);
168
+ node.style.left = left + "px";
169
+ if (where == "over") top = pos.y;
170
+ else if (where == "near") {
171
+ var vspace = Math.max(scroller.offsetHeight, lines.length * lineHeight()),
172
+ hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
173
+ if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
174
+ top = pos.y - node.offsetHeight;
175
+ if (left + node.offsetWidth > hspace)
176
+ left = hspace - node.offsetWidth;
177
+ }
178
+ node.style.top = (top + paddingTop()) + "px";
179
+ node.style.left = (left + paddingLeft()) + "px";
180
+ if (scroll)
181
+ scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
182
+ },
183
+
184
+ lineCount: function() {return lines.length;},
185
+ getCursor: function(start) {
186
+ if (start == null) start = sel.inverted;
187
+ return copyPos(start ? sel.from : sel.to);
188
+ },
189
+ somethingSelected: function() {return !posEq(sel.from, sel.to);},
190
+ setCursor: operation(function(line, ch) {
191
+ if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch);
192
+ else setCursor(line, ch);
193
+ }),
194
+ setSelection: operation(function(from, to) {setSelection(clipPos(from), clipPos(to || from));}),
195
+ getLine: function(line) {if (isLine(line)) return lines[line].text;},
196
+ setLine: operation(function(line, text) {
197
+ if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: lines[line].text.length});
198
+ }),
199
+ removeLine: operation(function(line) {
200
+ if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
201
+ }),
202
+ replaceRange: operation(replaceRange),
203
+ getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
204
+
205
+ operation: function(f){return operation(f)();},
206
+ refresh: function(){updateDisplay(true);},
207
+ getInputField: function(){return input;},
208
+ getWrapperElement: function(){return wrapper;},
209
+ getScrollerElement: function(){return scroller;},
210
+ getGutterElement: function(){return gutter;}
211
+ };
212
+
213
+ function setValue(code) {
214
+ history = null;
215
+ var top = {line: 0, ch: 0};
216
+ updateLines(top, {line: lines.length - 1, ch: lines[lines.length-1].text.length},
217
+ splitLines(code), top, top);
218
+ history = new History();
219
+ updateInput = true;
220
+ }
221
+ function getValue(code) {
222
+ var text = [];
223
+ for (var i = 0, l = lines.length; i < l; ++i)
224
+ text.push(lines[i].text);
225
+ return text.join("\n");
226
+ }
227
+
228
+ function onMouseDown(e) {
229
+ // Check whether this is a click in a widget
230
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
231
+ if (n.parentNode == code && n != mover) return;
232
+ var ld = lastDoubleClick; lastDoubleClick = null;
233
+ // First, see if this is a click in the gutter
234
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
235
+ if (n.parentNode == gutterText) {
236
+ if (options.onGutterClick)
237
+ options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
238
+ return e_preventDefault(e);
239
+ }
240
+
241
+ var start = posFromMouse(e);
242
+
243
+ switch (e_button(e)) {
244
+ case 3:
245
+ if (gecko && !mac) onContextMenu(e);
246
+ return;
247
+ case 2:
248
+ if (start) setCursor(start.line, start.ch, true);
249
+ return;
250
+ }
251
+ // For button 1, if it was clicked inside the editor
252
+ // (posFromMouse returning non-null), we have to adjust the
253
+ // selection.
254
+ if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
255
+
256
+ if (!focused) onFocus();
257
+ e_preventDefault(e);
258
+ if (ld && +new Date - ld < 400) return selectLine(start.line);
259
+
260
+ setCursor(start.line, start.ch, true);
261
+ var last = start, going;
262
+ // And then we have to see if it's a drag event, in which case
263
+ // the dragged-over text must be selected.
264
+ function end() {
265
+ focusInput();
266
+ updateInput = true;
267
+ move(); up();
268
+ }
269
+ function extend(e) {
270
+ var cur = posFromMouse(e, true);
271
+ if (cur && !posEq(cur, last)) {
272
+ if (!focused) onFocus();
273
+ last = cur;
274
+ setSelectionUser(start, cur);
275
+ updateInput = false;
276
+ var visible = visibleLines();
277
+ if (cur.line >= visible.to || cur.line < visible.from)
278
+ going = setTimeout(operation(function(){extend(e);}), 150);
279
+ }
280
+ }
281
+
282
+ var move = connect(targetDocument, "mousemove", operation(function(e) {
283
+ clearTimeout(going);
284
+ e_preventDefault(e);
285
+ extend(e);
286
+ }), true);
287
+ var up = connect(targetDocument, "mouseup", operation(function(e) {
288
+ clearTimeout(going);
289
+ var cur = posFromMouse(e);
290
+ if (cur) setSelectionUser(start, cur);
291
+ e_preventDefault(e);
292
+ end();
293
+ }), true);
294
+ }
295
+ function onDblClick(e) {
296
+ var pos = posFromMouse(e);
297
+ if (!pos) return;
298
+ selectWordAt(pos);
299
+ e_preventDefault(e);
300
+ lastDoubleClick = +new Date;
301
+ }
302
+ function onDrop(e) {
303
+ e.preventDefault();
304
+ var pos = posFromMouse(e, true), files = e.dataTransfer.files;
305
+ if (!pos || options.readOnly) return;
306
+ if (files && files.length && window.FileReader && window.File) {
307
+ function loadFile(file, i) {
308
+ var reader = new FileReader;
309
+ reader.onload = function() {
310
+ text[i] = reader.result;
311
+ if (++read == n) replaceRange(text.join(""), clipPos(pos), clipPos(pos));
312
+ };
313
+ reader.readAsText(file);
314
+ }
315
+ var n = files.length, text = Array(n), read = 0;
316
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
317
+ }
318
+ else {
319
+ try {
320
+ var text = e.dataTransfer.getData("Text");
321
+ if (text) replaceRange(text, pos, pos);
322
+ }
323
+ catch(e){}
324
+ }
325
+ }
326
+ function onKeyDown(e) {
327
+ if (!focused) onFocus();
328
+
329
+ var code = e.keyCode;
330
+ // IE does strange things with escape.
331
+ if (ie && code == 27) { e.returnValue = false; }
332
+ // Tries to detect ctrl on non-mac, cmd on mac.
333
+ var mod = (mac ? e.metaKey : e.ctrlKey) && !e.altKey, anyMod = e.ctrlKey || e.altKey || e.metaKey;
334
+ if (code == 16 || e.shiftKey) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
335
+ else shiftSelecting = null;
336
+ // First give onKeyEvent option a chance to handle this.
337
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
338
+
339
+ if (code == 33 || code == 34) {scrollPage(code == 34); return e_preventDefault(e);} // page up/down
340
+ if (mod && ((code == 36 || code == 35) || // ctrl-home/end
341
+ mac && (code == 38 || code == 40))) { // cmd-up/down
342
+ scrollEnd(code == 36 || code == 38); return e_preventDefault(e);
343
+ }
344
+ if (mod && code == 65) {selectAll(); return e_preventDefault(e);} // ctrl-a
345
+ if (!options.readOnly) {
346
+ if (!anyMod && code == 13) {return;} // enter
347
+ if (!anyMod && code == 9 && handleTab(e.shiftKey)) return e_preventDefault(e); // tab
348
+ if (mod && code == 90) {undo(); return e_preventDefault(e);} // ctrl-z
349
+ if (mod && ((e.shiftKey && code == 90) || code == 89)) {redo(); return e_preventDefault(e);} // ctrl-shift-z, ctrl-y
350
+ }
351
+ if (code == 36) { if (options.smartHome) { smartHome(); return e_preventDefault(e); } }
352
+
353
+ // Key id to use in the movementKeys map. We also pass it to
354
+ // fastPoll in order to 'self learn'. We need this because
355
+ // reducedSelection, the hack where we collapse the selection to
356
+ // its start when it is inverted and a movement key is pressed
357
+ // (and later restore it again), shouldn't be used for
358
+ // non-movement keys.
359
+ curKeyId = (mod ? "c" : "") + (e.altKey ? "a" : "") + code;
360
+ if (sel.inverted && movementKeys[curKeyId] === true) {
361
+ var range = selRange(input);
362
+ if (range) {
363
+ reducedSelection = {anchor: range.start};
364
+ setSelRange(input, range.start, range.start);
365
+ }
366
+ }
367
+ // Don't save the key as a movementkey unless it had a modifier
368
+ if (!mod && !e.altKey) curKeyId = null;
369
+ fastPoll(curKeyId);
370
+ }
371
+ function onKeyUp(e) {
372
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
373
+ if (reducedSelection) {
374
+ reducedSelection = null;
375
+ updateInput = true;
376
+ }
377
+ if (e.keyCode == 16) shiftSelecting = null;
378
+ }
379
+ function onKeyPress(e) {
380
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
381
+ if (options.electricChars && mode.electricChars) {
382
+ var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode);
383
+ if (mode.electricChars.indexOf(ch) > -1)
384
+ setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50);
385
+ }
386
+ var code = e.keyCode;
387
+ // Re-stop tab and enter. Necessary on some browsers.
388
+ if (code == 13) {if (!options.readOnly) handleEnter(); e_preventDefault(e);}
389
+ else if (!e.ctrlKey && !e.altKey && !e.metaKey && code == 9 && options.tabMode != "default") e_preventDefault(e);
390
+ else fastPoll(curKeyId);
391
+ }
392
+
393
+ function onFocus() {
394
+ if (options.readOnly == "nocursor") return;
395
+ if (!focused) {
396
+ if (options.onFocus) options.onFocus(instance);
397
+ focused = true;
398
+ if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
399
+ wrapper.className += " CodeMirror-focused";
400
+ if (!leaveInputAlone) prepareInput();
401
+ }
402
+ slowPoll();
403
+ restartBlink();
404
+ }
405
+ function onBlur() {
406
+ if (focused) {
407
+ if (options.onBlur) options.onBlur(instance);
408
+ focused = false;
409
+ wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
410
+ }
411
+ clearInterval(blinker);
412
+ setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
413
+ }
414
+
415
+ // Replace the range from from to to by the strings in newText.
416
+ // Afterwards, set the selection to selFrom, selTo.
417
+ function updateLines(from, to, newText, selFrom, selTo) {
418
+ if (history) {
419
+ var old = [];
420
+ for (var i = from.line, e = to.line + 1; i < e; ++i) old.push(lines[i].text);
421
+ history.addChange(from.line, newText.length, old);
422
+ while (history.done.length > options.undoDepth) history.done.shift();
423
+ }
424
+ updateLinesNoUndo(from, to, newText, selFrom, selTo);
425
+ }
426
+ function unredoHelper(from, to) {
427
+ var change = from.pop();
428
+ if (change) {
429
+ var replaced = [], end = change.start + change.added;
430
+ for (var i = change.start; i < end; ++i) replaced.push(lines[i].text);
431
+ to.push({start: change.start, added: change.old.length, old: replaced});
432
+ var pos = clipPos({line: change.start + change.old.length - 1,
433
+ ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
434
+ updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: lines[end-1].text.length}, change.old, pos, pos);
435
+ updateInput = true;
436
+ }
437
+ }
438
+ function undo() {unredoHelper(history.done, history.undone);}
439
+ function redo() {unredoHelper(history.undone, history.done);}
440
+
441
+ function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
442
+ var recomputeMaxLength = false, maxLineLength = maxLine.length;
443
+ for (var i = from.line; i <= to.line; ++i) {
444
+ if (lines[i].text.length == maxLineLength) {recomputeMaxLength = true; break;}
445
+ }
446
+
447
+ var nlines = to.line - from.line, firstLine = lines[from.line], lastLine = lines[to.line];
448
+ // First adjust the line structure, taking some care to leave highlighting intact.
449
+ if (firstLine == lastLine) {
450
+ if (newText.length == 1)
451
+ firstLine.replace(from.ch, to.ch, newText[0]);
452
+ else {
453
+ lastLine = firstLine.split(to.ch, newText[newText.length-1]);
454
+ var spliceargs = [from.line + 1, nlines];
455
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
456
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
457
+ spliceargs.push(lastLine);
458
+ lines.splice.apply(lines, spliceargs);
459
+ }
460
+ }
461
+ else if (newText.length == 1) {
462
+ firstLine.replace(from.ch, firstLine.text.length, newText[0] + lastLine.text.slice(to.ch));
463
+ lines.splice(from.line + 1, nlines);
464
+ }
465
+ else {
466
+ var spliceargs = [from.line + 1, nlines - 1];
467
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
468
+ lastLine.replace(0, to.ch, newText[newText.length-1]);
469
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
470
+ lines.splice.apply(lines, spliceargs);
471
+ }
472
+
473
+
474
+ for (var i = from.line, e = i + newText.length; i < e; ++i) {
475
+ var l = lines[i].text;
476
+ if (l.length > maxLineLength) {
477
+ maxLine = l; maxLineLength = l.length; maxWidth = null;
478
+ recomputeMaxLength = false;
479
+ }
480
+ }
481
+ if (recomputeMaxLength) {
482
+ maxLineLength = 0; maxLine = ""; maxWidth = null;
483
+ for (var i = 0, e = lines.length; i < e; ++i) {
484
+ var l = lines[i].text;
485
+ if (l.length > maxLineLength) {
486
+ maxLineLength = l.length; maxLine = l;
487
+ }
488
+ }
489
+ }
490
+
491
+ // Add these lines to the work array, so that they will be
492
+ // highlighted. Adjust work lines if lines were added/removed.
493
+ var newWork = [], lendiff = newText.length - nlines - 1;
494
+ for (var i = 0, l = work.length; i < l; ++i) {
495
+ var task = work[i];
496
+ if (task < from.line) newWork.push(task);
497
+ else if (task > to.line) newWork.push(task + lendiff);
498
+ }
499
+ if (newText.length < 5) {
500
+ highlightLines(from.line, from.line + newText.length);
501
+ newWork.push(from.line + newText.length);
502
+ } else {
503
+ newWork.push(from.line);
504
+ }
505
+ work = newWork;
506
+ startWorker(100);
507
+ // Remember that these lines changed, for updating the display
508
+ changes.push({from: from.line, to: to.line + 1, diff: lendiff});
509
+ textChanged = {from: from, to: to, text: newText};
510
+
511
+ // Update the selection
512
+ function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
513
+ setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
514
+
515
+ // Make sure the scroll-size div has the correct height.
516
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
517
+ }
518
+
519
+ function replaceRange(code, from, to) {
520
+ from = clipPos(from);
521
+ if (!to) to = from; else to = clipPos(to);
522
+ code = splitLines(code);
523
+ function adjustPos(pos) {
524
+ if (posLess(pos, from)) return pos;
525
+ if (!posLess(to, pos)) return end;
526
+ var line = pos.line + code.length - (to.line - from.line) - 1;
527
+ var ch = pos.ch;
528
+ if (pos.line == to.line)
529
+ ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
530
+ return {line: line, ch: ch};
531
+ }
532
+ var end;
533
+ replaceRange1(code, from, to, function(end1) {
534
+ end = end1;
535
+ return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
536
+ });
537
+ return end;
538
+ }
539
+ function replaceSelection(code, collapse) {
540
+ replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
541
+ if (collapse == "end") return {from: end, to: end};
542
+ else if (collapse == "start") return {from: sel.from, to: sel.from};
543
+ else return {from: sel.from, to: end};
544
+ });
545
+ }
546
+ function replaceRange1(code, from, to, computeSel) {
547
+ var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
548
+ var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
549
+ updateLines(from, to, code, newSel.from, newSel.to);
550
+ }
551
+
552
+ function getRange(from, to) {
553
+ var l1 = from.line, l2 = to.line;
554
+ if (l1 == l2) return lines[l1].text.slice(from.ch, to.ch);
555
+ var code = [lines[l1].text.slice(from.ch)];
556
+ for (var i = l1 + 1; i < l2; ++i) code.push(lines[i].text);
557
+ code.push(lines[l2].text.slice(0, to.ch));
558
+ return code.join("\n");
559
+ }
560
+ function getSelection() {
561
+ return getRange(sel.from, sel.to);
562
+ }
563
+
564
+ var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
565
+ function slowPoll() {
566
+ if (pollingFast) return;
567
+ poll.set(2000, function() {
568
+ startOperation();
569
+ readInput();
570
+ if (focused) slowPoll();
571
+ endOperation();
572
+ });
573
+ }
574
+ function fastPoll(keyId) {
575
+ var missed = false;
576
+ pollingFast = true;
577
+ function p() {
578
+ startOperation();
579
+ var changed = readInput();
580
+ if (changed && keyId) {
581
+ if (changed == "moved" && movementKeys[keyId] == null) movementKeys[keyId] = true;
582
+ if (changed == "changed") movementKeys[keyId] = false;
583
+ }
584
+ if (!changed && !missed) {missed = true; poll.set(80, p);}
585
+ else {pollingFast = false; slowPoll();}
586
+ endOperation();
587
+ }
588
+ poll.set(20, p);
589
+ }
590
+
591
+ // Inspects the textarea, compares its state (content, selection)
592
+ // to the data in the editing variable, and updates the editor
593
+ // content or cursor if something changed.
594
+ function readInput() {
595
+ if (leaveInputAlone || !focused) return;
596
+ var changed = false, text = input.value, sr = selRange(input);
597
+ if (!sr) return false;
598
+ var changed = editing.text != text, rs = reducedSelection;
599
+ var moved = changed || sr.start != editing.start || sr.end != (rs ? editing.start : editing.end);
600
+ if (!moved && !rs) return false;
601
+ if (changed) {
602
+ shiftSelecting = reducedSelection = null;
603
+ if (options.readOnly) {updateInput = true; return "changed";}
604
+ }
605
+
606
+ // Compute selection start and end based on start/end offsets in textarea
607
+ function computeOffset(n, startLine) {
608
+ var pos = 0;
609
+ for (;;) {
610
+ var found = text.indexOf("\n", pos);
611
+ if (found == -1 || (text.charAt(found-1) == "\r" ? found - 1 : found) >= n)
612
+ return {line: startLine, ch: n - pos};
613
+ ++startLine;
614
+ pos = found + 1;
615
+ }
616
+ }
617
+ var from = computeOffset(sr.start, editing.from),
618
+ to = computeOffset(sr.end, editing.from);
619
+ // Here we have to take the reducedSelection hack into account,
620
+ // so that you can, for example, press shift-up at the start of
621
+ // your selection and have the right thing happen.
622
+ if (rs) {
623
+ var head = sr.start == rs.anchor ? to : from;
624
+ var tail = shiftSelecting ? sel.to : sr.start == rs.anchor ? from : to;
625
+ if (sel.inverted = posLess(head, tail)) { from = head; to = tail; }
626
+ else { reducedSelection = null; from = tail; to = head; }
627
+ }
628
+
629
+ // In some cases (cursor on same line as before), we don't have
630
+ // to update the textarea content at all.
631
+ if (from.line == to.line && from.line == sel.from.line && from.line == sel.to.line && !shiftSelecting)
632
+ updateInput = false;
633
+
634
+ // Magic mess to extract precise edited range from the changed
635
+ // string.
636
+ if (changed) {
637
+ var start = 0, end = text.length, len = Math.min(end, editing.text.length);
638
+ var c, line = editing.from, nl = -1;
639
+ while (start < len && (c = text.charAt(start)) == editing.text.charAt(start)) {
640
+ ++start;
641
+ if (c == "\n") {line++; nl = start;}
642
+ }
643
+ var ch = nl > -1 ? start - nl : start, endline = editing.to - 1, edend = editing.text.length;
644
+ for (;;) {
645
+ c = editing.text.charAt(edend);
646
+ if (text.charAt(end) != c) {++end; ++edend; break;}
647
+ if (c == "\n") endline--;
648
+ if (edend <= start || end <= start) break;
649
+ --end; --edend;
650
+ }
651
+ var nl = editing.text.lastIndexOf("\n", edend - 1), endch = nl == -1 ? edend : edend - nl - 1;
652
+ updateLines({line: line, ch: ch}, {line: endline, ch: endch}, splitLines(text.slice(start, end)), from, to);
653
+ if (line != endline || from.line != line) updateInput = true;
654
+ }
655
+ else setSelection(from, to);
656
+
657
+ editing.text = text; editing.start = sr.start; editing.end = sr.end;
658
+ return changed ? "changed" : moved ? "moved" : false;
659
+ }
660
+
661
+ // Set the textarea content and selection range to match the
662
+ // editor state.
663
+ function prepareInput() {
664
+ var text = [];
665
+ var from = Math.max(0, sel.from.line - 1), to = Math.min(lines.length, sel.to.line + 2);
666
+ for (var i = from; i < to; ++i) text.push(lines[i].text);
667
+ text = input.value = text.join(lineSep);
668
+ var startch = sel.from.ch, endch = sel.to.ch;
669
+ for (var i = from; i < sel.from.line; ++i)
670
+ startch += lineSep.length + lines[i].text.length;
671
+ for (var i = from; i < sel.to.line; ++i)
672
+ endch += lineSep.length + lines[i].text.length;
673
+ editing = {text: text, from: from, to: to, start: startch, end: endch};
674
+ setSelRange(input, startch, reducedSelection ? startch : endch);
675
+ }
676
+ function focusInput() {
677
+ if (options.readOnly != "nocursor") input.focus();
678
+ }
679
+
680
+ function scrollEditorIntoView() {
681
+ if (!cursor.getBoundingClientRect) return;
682
+ var rect = cursor.getBoundingClientRect();
683
+ var winH = window.innerHeight || document.body.offsetHeight || document.documentElement.offsetHeight;
684
+ if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView();
685
+ }
686
+ function scrollCursorIntoView() {
687
+ var cursor = localCoords(sel.inverted ? sel.from : sel.to);
688
+ return scrollIntoView(cursor.x, cursor.y, cursor.x, cursor.yBot);
689
+ }
690
+ function scrollIntoView(x1, y1, x2, y2) {
691
+ var pl = paddingLeft(), pt = paddingTop(), lh = lineHeight();
692
+ y1 += pt; y2 += pt; x1 += pl; x2 += pl;
693
+ var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
694
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
695
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
696
+
697
+ var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
698
+ var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
699
+ if (x1 < screenleft + gutterw) {
700
+ if (x1 < 50) x1 = 0;
701
+ scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw);
702
+ scrolled = true;
703
+ }
704
+ else if (x2 > screenw + screenleft) {
705
+ scroller.scrollLeft = x2 + 10 - screenw;
706
+ scrolled = true;
707
+ if (x2 > code.clientWidth) result = false;
708
+ }
709
+ if (scrolled && options.onScroll) options.onScroll(instance);
710
+ return result;
711
+ }
712
+
713
+ function visibleLines() {
714
+ var lh = lineHeight(), top = scroller.scrollTop - paddingTop();
715
+ return {from: Math.min(lines.length, Math.max(0, Math.floor(top / lh))),
716
+ to: Math.min(lines.length, Math.ceil((top + scroller.clientHeight) / lh))};
717
+ }
718
+ // Uses a set of changes plus the current scroll position to
719
+ // determine which DOM updates have to be made, and makes the
720
+ // updates.
721
+ function updateDisplay(changes) {
722
+ if (!scroller.clientWidth) {
723
+ showingFrom = showingTo = 0;
724
+ return;
725
+ }
726
+ // First create a range of theoretically intact lines, and punch
727
+ // holes in that using the change info.
728
+ var intact = changes === true ? [] : [{from: showingFrom, to: showingTo, domStart: 0}];
729
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
730
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
731
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
732
+ var range = intact[j];
733
+ if (change.to <= range.from)
734
+ intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart});
735
+ else if (range.to <= change.from)
736
+ intact2.push(range);
737
+ else {
738
+ if (change.from > range.from)
739
+ intact2.push({from: range.from, to: change.from, domStart: range.domStart})
740
+ if (change.to < range.to)
741
+ intact2.push({from: change.to + diff, to: range.to + diff,
742
+ domStart: range.domStart + (change.to - range.from)});
743
+ }
744
+ }
745
+ intact = intact2;
746
+ }
747
+
748
+ // Then, determine which lines we'd want to see, and which
749
+ // updates have to be made to get there.
750
+ var visible = visibleLines();
751
+ var from = Math.min(showingFrom, Math.max(visible.from - 3, 0)),
752
+ to = Math.min(lines.length, Math.max(showingTo, visible.to + 3)),
753
+ updates = [], domPos = 0, domEnd = showingTo - showingFrom, pos = from, changedLines = 0;
754
+
755
+ for (var i = 0, l = intact.length; i < l; ++i) {
756
+ var range = intact[i];
757
+ if (range.to <= from) continue;
758
+ if (range.from >= to) break;
759
+ if (range.domStart > domPos || range.from > pos) {
760
+ updates.push({from: pos, to: range.from, domSize: range.domStart - domPos, domStart: domPos});
761
+ changedLines += range.from - pos;
762
+ }
763
+ pos = range.to;
764
+ domPos = range.domStart + (range.to - range.from);
765
+ }
766
+ if (domPos != domEnd || pos != to) {
767
+ changedLines += Math.abs(to - pos);
768
+ updates.push({from: pos, to: to, domSize: domEnd - domPos, domStart: domPos});
769
+ }
770
+
771
+ if (!updates.length) return;
772
+ lineDiv.style.display = "none";
773
+ // If more than 30% of the screen needs update, just do a full
774
+ // redraw (which is quicker than patching)
775
+ if (changedLines > (visible.to - visible.from) * .3)
776
+ refreshDisplay(from = Math.max(visible.from - 10, 0), to = Math.min(visible.to + 7, lines.length));
777
+ // Otherwise, only update the stuff that needs updating.
778
+ else
779
+ patchDisplay(updates);
780
+ lineDiv.style.display = "";
781
+
782
+ // Position the mover div to align with the lines it's supposed
783
+ // to be showing (which will cover the visible display)
784
+ var different = from != showingFrom || to != showingTo || lastHeight != scroller.clientHeight;
785
+ showingFrom = from; showingTo = to;
786
+ mover.style.top = (from * lineHeight()) + "px";
787
+ if (different) {
788
+ lastHeight = scroller.clientHeight;
789
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
790
+ }
791
+ if (different || updates.length) updateGutter();
792
+
793
+ if (maxWidth == null) maxWidth = stringWidth(maxLine);
794
+ if (maxWidth > scroller.clientWidth) {
795
+ lineSpace.style.width = maxWidth + "px";
796
+ // Needed to prevent odd wrapping/hiding of widgets placed in here.
797
+ code.style.width = "";
798
+ code.style.width = scroller.scrollWidth + "px";
799
+ } else {
800
+ lineSpace.style.width = code.style.width = "";
801
+ }
802
+
803
+ // Since this is all rather error prone, it is honoured with the
804
+ // only assertion in the whole file.
805
+ if (lineDiv.childNodes.length != showingTo - showingFrom)
806
+ throw new Error("BAD PATCH! " + JSON.stringify(updates) + " size=" + (showingTo - showingFrom) +
807
+ " nodes=" + lineDiv.childNodes.length);
808
+ updateCursor();
809
+ }
810
+
811
+ function refreshDisplay(from, to) {
812
+ var html = [], start = {line: from, ch: 0}, inSel = posLess(sel.from, start) && !posLess(sel.to, start);
813
+ for (var i = from; i < to; ++i) {
814
+ var ch1 = null, ch2 = null;
815
+ if (inSel) {
816
+ ch1 = 0;
817
+ if (sel.to.line == i) {inSel = false; ch2 = sel.to.ch;}
818
+ }
819
+ else if (sel.from.line == i) {
820
+ if (sel.to.line == i) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
821
+ else {inSel = true; ch1 = sel.from.ch;}
822
+ }
823
+ html.push(lines[i].getHTML(ch1, ch2, true));
824
+ }
825
+ lineDiv.innerHTML = html.join("");
826
+ }
827
+ function patchDisplay(updates) {
828
+ // Slightly different algorithm for IE (badInnerHTML), since
829
+ // there .innerHTML on PRE nodes is dumb, and discards
830
+ // whitespace.
831
+ var sfrom = sel.from.line, sto = sel.to.line, off = 0,
832
+ scratch = badInnerHTML && targetDocument.createElement("div");
833
+ for (var i = 0, e = updates.length; i < e; ++i) {
834
+ var rec = updates[i];
835
+ var extra = (rec.to - rec.from) - rec.domSize;
836
+ var nodeAfter = lineDiv.childNodes[rec.domStart + rec.domSize + off] || null;
837
+ if (badInnerHTML)
838
+ for (var j = Math.max(-extra, rec.domSize); j > 0; --j)
839
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
840
+ else if (extra) {
841
+ for (var j = Math.max(0, extra); j > 0; --j)
842
+ lineDiv.insertBefore(targetDocument.createElement("pre"), nodeAfter);
843
+ for (var j = Math.max(0, -extra); j > 0; --j)
844
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
845
+ }
846
+ var node = lineDiv.childNodes[rec.domStart + off], inSel = sfrom < rec.from && sto >= rec.from;
847
+ for (var j = rec.from; j < rec.to; ++j) {
848
+ var ch1 = null, ch2 = null;
849
+ if (inSel) {
850
+ ch1 = 0;
851
+ if (sto == j) {inSel = false; ch2 = sel.to.ch;}
852
+ }
853
+ else if (sfrom == j) {
854
+ if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
855
+ else {inSel = true; ch1 = sel.from.ch;}
856
+ }
857
+ if (badInnerHTML) {
858
+ scratch.innerHTML = lines[j].getHTML(ch1, ch2, true);
859
+ lineDiv.insertBefore(scratch.firstChild, nodeAfter);
860
+ }
861
+ else {
862
+ node.innerHTML = lines[j].getHTML(ch1, ch2, false);
863
+ node.className = lines[j].className || "";
864
+ node = node.nextSibling;
865
+ }
866
+ }
867
+ off += extra;
868
+ }
869
+ }
870
+
871
+ function updateGutter() {
872
+ if (!options.gutter && !options.lineNumbers) return;
873
+ var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
874
+ gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
875
+ var html = [];
876
+ for (var i = showingFrom; i < Math.max(showingTo, showingFrom + 1); ++i) {
877
+ var marker = lines[i].gutterMarker;
878
+ var text = options.lineNumbers ? i + options.firstLineNumber : null;
879
+ if (marker && marker.text)
880
+ text = marker.text.replace("%N%", text != null ? text : "");
881
+ else if (text == null)
882
+ text = "\u00a0";
883
+ html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text, "</pre>");
884
+ }
885
+ gutter.style.display = "none";
886
+ gutterText.innerHTML = html.join("");
887
+ var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
888
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
889
+ if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
890
+ gutter.style.display = "";
891
+ lineSpace.style.marginLeft = gutter.offsetWidth + "px";
892
+ }
893
+ function updateCursor() {
894
+ var head = sel.inverted ? sel.from : sel.to, lh = lineHeight();
895
+ var x = charX(head.line, head.ch);
896
+ inputDiv.style.top = (head.line * lh - scroller.scrollTop) + "px";
897
+ inputDiv.style.left = (x - scroller.scrollLeft) + "px";
898
+ if (posEq(sel.from, sel.to)) {
899
+ cursor.style.top = (head.line - showingFrom) * lh + "px";
900
+ cursor.style.left = x + "px";
901
+ cursor.style.display = "";
902
+ }
903
+ else cursor.style.display = "none";
904
+ }
905
+
906
+ function setSelectionUser(from, to) {
907
+ var sh = shiftSelecting && clipPos(shiftSelecting);
908
+ if (sh) {
909
+ if (posLess(sh, from)) from = sh;
910
+ else if (posLess(to, sh)) to = sh;
911
+ }
912
+ setSelection(from, to);
913
+ }
914
+ // Update the selection. Last two args are only used by
915
+ // updateLines, since they have to be expressed in the line
916
+ // numbers before the update.
917
+ function setSelection(from, to, oldFrom, oldTo) {
918
+ if (posEq(sel.from, from) && posEq(sel.to, to)) return;
919
+ if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
920
+
921
+ if (posEq(from, to)) sel.inverted = false;
922
+ else if (posEq(from, sel.to)) sel.inverted = false;
923
+ else if (posEq(to, sel.from)) sel.inverted = true;
924
+
925
+ // Some ugly logic used to only mark the lines that actually did
926
+ // see a change in selection as changed, rather than the whole
927
+ // selected range.
928
+ if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
929
+ if (posEq(from, to)) {
930
+ if (!posEq(sel.from, sel.to))
931
+ changes.push({from: oldFrom, to: oldTo + 1});
932
+ }
933
+ else if (posEq(sel.from, sel.to)) {
934
+ changes.push({from: from.line, to: to.line + 1});
935
+ }
936
+ else {
937
+ if (!posEq(from, sel.from)) {
938
+ if (from.line < oldFrom)
939
+ changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
940
+ else
941
+ changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
942
+ }
943
+ if (!posEq(to, sel.to)) {
944
+ if (to.line < oldTo)
945
+ changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
946
+ else
947
+ changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
948
+ }
949
+ }
950
+ sel.from = from; sel.to = to;
951
+ selectionChanged = true;
952
+ }
953
+ function setCursor(line, ch, user) {
954
+ var pos = clipPos({line: line, ch: ch || 0});
955
+ (user ? setSelectionUser : setSelection)(pos, pos);
956
+ }
957
+
958
+ function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));}
959
+ function clipPos(pos) {
960
+ if (pos.line < 0) return {line: 0, ch: 0};
961
+ if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length};
962
+ var ch = pos.ch, linelen = lines[pos.line].text.length;
963
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
964
+ else if (ch < 0) return {line: pos.line, ch: 0};
965
+ else return pos;
966
+ }
967
+
968
+ function scrollPage(down) {
969
+ var linesPerPage = Math.floor(scroller.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to;
970
+ setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true);
971
+ }
972
+ function scrollEnd(top) {
973
+ var pos = top ? {line: 0, ch: 0} : {line: lines.length - 1, ch: lines[lines.length-1].text.length};
974
+ setSelectionUser(pos, pos);
975
+ }
976
+ function selectAll() {
977
+ var endLine = lines.length - 1;
978
+ setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length});
979
+ }
980
+ function selectWordAt(pos) {
981
+ var line = lines[pos.line].text;
982
+ var start = pos.ch, end = pos.ch;
983
+ while (start > 0 && /\w/.test(line.charAt(start - 1))) --start;
984
+ while (end < line.length && /\w/.test(line.charAt(end))) ++end;
985
+ setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
986
+ }
987
+ function selectLine(line) {
988
+ setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length});
989
+ }
990
+ function handleEnter() {
991
+ replaceSelection("\n", "end");
992
+ if (options.enterMode != "flat")
993
+ indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart");
994
+ }
995
+ function handleTab(shift) {
996
+ function indentSelected(mode) {
997
+ if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
998
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
999
+ for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
1000
+ }
1001
+ shiftSelecting = null;
1002
+ switch (options.tabMode) {
1003
+ case "default":
1004
+ return false;
1005
+ case "indent":
1006
+ indentSelected("smart");
1007
+ break;
1008
+ case "classic":
1009
+ if (posEq(sel.from, sel.to)) {
1010
+ if (shift) indentLine(sel.from.line, "smart");
1011
+ else replaceSelection("\t", "end");
1012
+ break;
1013
+ }
1014
+ case "shift":
1015
+ indentSelected(shift ? "subtract" : "add");
1016
+ break;
1017
+ }
1018
+ return true;
1019
+ }
1020
+ function smartHome() {
1021
+ var firstNonWS = Math.max(0, lines[sel.from.line].text.search(/\S/));
1022
+ setCursor(sel.from.line, sel.from.ch <= firstNonWS && sel.from.ch ? 0 : firstNonWS, true);
1023
+ }
1024
+
1025
+ function indentLine(n, how) {
1026
+ if (how == "smart") {
1027
+ if (!mode.indent) how = "prev";
1028
+ else var state = getStateBefore(n);
1029
+ }
1030
+
1031
+ var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation;
1032
+ if (how == "prev") {
1033
+ if (n) indentation = lines[n-1].indentation();
1034
+ else indentation = 0;
1035
+ }
1036
+ else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length));
1037
+ else if (how == "add") indentation = curSpace + options.indentUnit;
1038
+ else if (how == "subtract") indentation = curSpace - options.indentUnit;
1039
+ indentation = Math.max(0, indentation);
1040
+ var diff = indentation - curSpace;
1041
+
1042
+ if (!diff) {
1043
+ if (sel.from.line != n && sel.to.line != n) return;
1044
+ var indentString = curSpaceString;
1045
+ }
1046
+ else {
1047
+ var indentString = "", pos = 0;
1048
+ if (options.indentWithTabs)
1049
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
1050
+ while (pos < indentation) {++pos; indentString += " ";}
1051
+ }
1052
+
1053
+ replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1054
+ }
1055
+
1056
+ function loadMode() {
1057
+ mode = CodeMirror.getMode(options, options.mode);
1058
+ for (var i = 0, l = lines.length; i < l; ++i)
1059
+ lines[i].stateAfter = null;
1060
+ work = [0];
1061
+ startWorker();
1062
+ }
1063
+ function gutterChanged() {
1064
+ var visible = options.gutter || options.lineNumbers;
1065
+ gutter.style.display = visible ? "" : "none";
1066
+ if (visible) updateGutter();
1067
+ else lineDiv.parentNode.style.marginLeft = 0;
1068
+ }
1069
+
1070
+ function markText(from, to, className) {
1071
+ from = clipPos(from); to = clipPos(to);
1072
+ var accum = [];
1073
+ function add(line, from, to, className) {
1074
+ var line = lines[line], mark = line.addMark(from, to, className);
1075
+ mark.line = line;
1076
+ accum.push(mark);
1077
+ }
1078
+ if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1079
+ else {
1080
+ add(from.line, from.ch, null, className);
1081
+ for (var i = from.line + 1, e = to.line; i < e; ++i)
1082
+ add(i, 0, null, className);
1083
+ add(to.line, 0, to.ch, className);
1084
+ }
1085
+ changes.push({from: from.line, to: to.line + 1});
1086
+ return function() {
1087
+ var start, end;
1088
+ for (var i = 0; i < accum.length; ++i) {
1089
+ var mark = accum[i], found = indexOf(lines, mark.line);
1090
+ mark.line.removeMark(mark);
1091
+ if (found > -1) {
1092
+ if (start == null) start = found;
1093
+ end = found;
1094
+ }
1095
+ }
1096
+ if (start != null) changes.push({from: start, to: end + 1});
1097
+ };
1098
+ }
1099
+
1100
+ function addGutterMarker(line, text, className) {
1101
+ if (typeof line == "number") line = lines[clipLine(line)];
1102
+ line.gutterMarker = {text: text, style: className};
1103
+ updateGutter();
1104
+ return line;
1105
+ }
1106
+ function removeGutterMarker(line) {
1107
+ if (typeof line == "number") line = lines[clipLine(line)];
1108
+ line.gutterMarker = null;
1109
+ updateGutter();
1110
+ }
1111
+ function setLineClass(line, className) {
1112
+ if (typeof line == "number") {
1113
+ var no = line;
1114
+ line = lines[clipLine(line)];
1115
+ }
1116
+ else {
1117
+ var no = indexOf(lines, line);
1118
+ if (no == -1) return null;
1119
+ }
1120
+ if (line.className != className) {
1121
+ line.className = className;
1122
+ changes.push({from: no, to: no + 1});
1123
+ }
1124
+ return line;
1125
+ }
1126
+
1127
+ function lineInfo(line) {
1128
+ if (typeof line == "number") {
1129
+ var n = line;
1130
+ line = lines[line];
1131
+ if (!line) return null;
1132
+ }
1133
+ else {
1134
+ var n = indexOf(lines, line);
1135
+ if (n == -1) return null;
1136
+ }
1137
+ var marker = line.gutterMarker;
1138
+ return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style};
1139
+ }
1140
+
1141
+ function stringWidth(str) {
1142
+ measure.innerHTML = "<pre><span>x</span></pre>";
1143
+ measure.firstChild.firstChild.firstChild.nodeValue = str;
1144
+ return measure.firstChild.firstChild.offsetWidth || 10;
1145
+ }
1146
+ // These are used to go from pixel positions to character
1147
+ // positions, taking varying character widths into account.
1148
+ function charX(line, pos) {
1149
+ if (pos == 0) return 0;
1150
+ measure.innerHTML = "<pre><span>" + lines[line].getHTML(null, null, false, pos) + "</span></pre>";
1151
+ return measure.firstChild.firstChild.offsetWidth;
1152
+ }
1153
+ function charFromX(line, x) {
1154
+ if (x <= 0) return 0;
1155
+ var lineObj = lines[line], text = lineObj.text;
1156
+ function getX(len) {
1157
+ measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, len) + "</span></pre>";
1158
+ return measure.firstChild.firstChild.offsetWidth;
1159
+ }
1160
+ var from = 0, fromX = 0, to = text.length, toX;
1161
+ // Guess a suitable upper bound for our search.
1162
+ var estimated = Math.min(to, Math.ceil(x / stringWidth("x")));
1163
+ for (;;) {
1164
+ var estX = getX(estimated);
1165
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1166
+ else {toX = estX; to = estimated; break;}
1167
+ }
1168
+ if (x > toX) return to;
1169
+ // Try to guess a suitable lower bound as well.
1170
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1171
+ if (estX < x) {from = estimated; fromX = estX;}
1172
+ // Do a binary search between these bounds.
1173
+ for (;;) {
1174
+ if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1175
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1176
+ if (middleX > x) {to = middle; toX = middleX;}
1177
+ else {from = middle; fromX = middleX;}
1178
+ }
1179
+ }
1180
+
1181
+ function localCoords(pos, inLineWrap) {
1182
+ var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0);
1183
+ return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh};
1184
+ }
1185
+ function pageCoords(pos) {
1186
+ var local = localCoords(pos, true), off = eltOffset(lineSpace);
1187
+ return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1188
+ }
1189
+
1190
+ function lineHeight() {
1191
+ var nlines = lineDiv.childNodes.length;
1192
+ if (nlines) return (lineDiv.offsetHeight / nlines) || 1;
1193
+ measure.innerHTML = "<pre>x</pre>";
1194
+ return measure.firstChild.offsetHeight || 1;
1195
+ }
1196
+ function paddingTop() {return lineSpace.offsetTop;}
1197
+ function paddingLeft() {return lineSpace.offsetLeft;}
1198
+
1199
+ function posFromMouse(e, liberal) {
1200
+ var offW = eltOffset(scroller, true), x, y;
1201
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1202
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1203
+ // This is a mess of a heuristic to try and determine whether a
1204
+ // scroll-bar was clicked or not, and to return null if one was
1205
+ // (and !liberal).
1206
+ if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1207
+ return null;
1208
+ var offL = eltOffset(lineSpace, true);
1209
+ var line = showingFrom + Math.floor((y - offL.top) / lineHeight());
1210
+ return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)});
1211
+ }
1212
+ function onContextMenu(e) {
1213
+ var pos = posFromMouse(e);
1214
+ if (!pos || window.opera) return; // Opera is difficult.
1215
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1216
+ operation(setCursor)(pos.line, pos.ch);
1217
+
1218
+ var oldCSS = input.style.cssText;
1219
+ inputDiv.style.position = "absolute";
1220
+ input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1221
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1222
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1223
+ leaveInputAlone = true;
1224
+ var val = input.value = getSelection();
1225
+ focusInput();
1226
+ setSelRange(input, 0, input.value.length);
1227
+ function rehide() {
1228
+ var newVal = splitLines(input.value).join("\n");
1229
+ if (newVal != val) operation(replaceSelection)(newVal, "end");
1230
+ inputDiv.style.position = "relative";
1231
+ input.style.cssText = oldCSS;
1232
+ leaveInputAlone = false;
1233
+ prepareInput();
1234
+ slowPoll();
1235
+ }
1236
+
1237
+ if (gecko) {
1238
+ e_stop(e);
1239
+ var mouseup = connect(window, "mouseup", function() {
1240
+ mouseup();
1241
+ setTimeout(rehide, 20);
1242
+ }, true);
1243
+ }
1244
+ else {
1245
+ setTimeout(rehide, 50);
1246
+ }
1247
+ }
1248
+
1249
+ // Cursor-blinking
1250
+ function restartBlink() {
1251
+ clearInterval(blinker);
1252
+ var on = true;
1253
+ cursor.style.visibility = "";
1254
+ blinker = setInterval(function() {
1255
+ cursor.style.visibility = (on = !on) ? "" : "hidden";
1256
+ }, 650);
1257
+ }
1258
+
1259
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1260
+ function matchBrackets(autoclear) {
1261
+ var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1;
1262
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1263
+ if (!match) return;
1264
+ var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1265
+ for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1266
+ if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1267
+
1268
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1269
+ function scan(line, from, to) {
1270
+ if (!line.text) return;
1271
+ var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1272
+ for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1273
+ var text = st[i];
1274
+ if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1275
+ for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1276
+ if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1277
+ var match = matching[cur];
1278
+ if (match.charAt(1) == ">" == forward) stack.push(cur);
1279
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1280
+ else if (!stack.length) return {pos: pos, match: true};
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ for (var i = head.line, e = forward ? Math.min(i + 100, lines.length) : Math.max(-1, i - 100); i != e; i+=d) {
1286
+ var line = lines[i], first = i == head.line;
1287
+ var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1288
+ if (found) break;
1289
+ }
1290
+ if (!found) found = {pos: null, match: false};
1291
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1292
+ var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1293
+ two = found.pos != null
1294
+ ? markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style)
1295
+ : function() {};
1296
+ var clear = operation(function(){one(); two();});
1297
+ if (autoclear) setTimeout(clear, 800);
1298
+ else bracketHighlighted = clear;
1299
+ }
1300
+
1301
+ // Finds the line to start with when starting a parse. Tries to
1302
+ // find a line with a stateAfter, so that it can start with a
1303
+ // valid state. If that fails, it returns the line with the
1304
+ // smallest indentation, which tends to need the least context to
1305
+ // parse correctly.
1306
+ function findStartLine(n) {
1307
+ var minindent, minline;
1308
+ for (var search = n, lim = n - 40; search > lim; --search) {
1309
+ if (search == 0) return 0;
1310
+ var line = lines[search-1];
1311
+ if (line.stateAfter) return search;
1312
+ var indented = line.indentation();
1313
+ if (minline == null || minindent > indented) {
1314
+ minline = search - 1;
1315
+ minindent = indented;
1316
+ }
1317
+ }
1318
+ return minline;
1319
+ }
1320
+ function getStateBefore(n) {
1321
+ var start = findStartLine(n), state = start && lines[start-1].stateAfter;
1322
+ if (!state) state = startState(mode);
1323
+ else state = copyState(mode, state);
1324
+ for (var i = start; i < n; ++i) {
1325
+ var line = lines[i];
1326
+ line.highlight(mode, state);
1327
+ line.stateAfter = copyState(mode, state);
1328
+ }
1329
+ if (n < lines.length && !lines[n].stateAfter) work.push(n);
1330
+ return state;
1331
+ }
1332
+ function highlightLines(start, end) {
1333
+ var state = getStateBefore(start);
1334
+ for (var i = start; i < end; ++i) {
1335
+ var line = lines[i];
1336
+ line.highlight(mode, state);
1337
+ line.stateAfter = copyState(mode, state);
1338
+ }
1339
+ }
1340
+ function highlightWorker() {
1341
+ var end = +new Date + options.workTime;
1342
+ var foundWork = work.length;
1343
+ while (work.length) {
1344
+ if (!lines[showingFrom].stateAfter) var task = showingFrom;
1345
+ else var task = work.pop();
1346
+ if (task >= lines.length) continue;
1347
+ var start = findStartLine(task), state = start && lines[start-1].stateAfter;
1348
+ if (state) state = copyState(mode, state);
1349
+ else state = startState(mode);
1350
+
1351
+ var unchanged = 0, compare = mode.compareStates, realChange = false;
1352
+ for (var i = start, l = lines.length; i < l; ++i) {
1353
+ var line = lines[i], hadState = line.stateAfter;
1354
+ if (+new Date > end) {
1355
+ work.push(i);
1356
+ startWorker(options.workDelay);
1357
+ if (realChange) changes.push({from: task, to: i + 1});
1358
+ return;
1359
+ }
1360
+ var changed = line.highlight(mode, state);
1361
+ if (changed) realChange = true;
1362
+ line.stateAfter = copyState(mode, state);
1363
+ if (compare) {
1364
+ if (hadState && compare(hadState, state)) break;
1365
+ } else {
1366
+ if (changed !== false || !hadState) unchanged = 0;
1367
+ else if (++unchanged > 3) break;
1368
+ }
1369
+ }
1370
+ if (realChange) changes.push({from: task, to: i + 1});
1371
+ }
1372
+ if (foundWork && options.onHighlightComplete)
1373
+ options.onHighlightComplete(instance);
1374
+ }
1375
+ function startWorker(time) {
1376
+ if (!work.length) return;
1377
+ highlight.set(time, operation(highlightWorker));
1378
+ }
1379
+
1380
+ // Operations are used to wrap changes in such a way that each
1381
+ // change won't have to update the cursor and display (which would
1382
+ // be awkward, slow, and error-prone), but instead updates are
1383
+ // batched and then all combined and executed at once.
1384
+ function startOperation() {
1385
+ updateInput = null; changes = []; textChanged = selectionChanged = false;
1386
+ }
1387
+ function endOperation() {
1388
+ var reScroll = false;
1389
+ if (selectionChanged) reScroll = !scrollCursorIntoView();
1390
+ if (changes.length) updateDisplay(changes);
1391
+ else if (selectionChanged) updateCursor();
1392
+ if (reScroll) scrollCursorIntoView();
1393
+ if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1394
+
1395
+ // updateInput can be set to a boolean value to force/prevent an
1396
+ // update.
1397
+ if (focused && !leaveInputAlone &&
1398
+ (updateInput === true || (updateInput !== false && selectionChanged)))
1399
+ prepareInput();
1400
+
1401
+ if (selectionChanged && options.matchBrackets)
1402
+ setTimeout(operation(function() {
1403
+ if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1404
+ matchBrackets(false);
1405
+ }), 20);
1406
+ var tc = textChanged; // textChanged can be reset by cursoractivity callback
1407
+ if (selectionChanged && options.onCursorActivity)
1408
+ options.onCursorActivity(instance);
1409
+ if (tc && options.onChange && instance)
1410
+ options.onChange(instance, tc);
1411
+ }
1412
+ var nestedOperation = 0;
1413
+ function operation(f) {
1414
+ return function() {
1415
+ if (!nestedOperation++) startOperation();
1416
+ try {var result = f.apply(this, arguments);}
1417
+ finally {if (!--nestedOperation) endOperation();}
1418
+ return result;
1419
+ };
1420
+ }
1421
+
1422
+ function SearchCursor(query, pos, caseFold) {
1423
+ this.atOccurrence = false;
1424
+ if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
1425
+
1426
+ if (pos && typeof pos == "object") pos = clipPos(pos);
1427
+ else pos = {line: 0, ch: 0};
1428
+ this.pos = {from: pos, to: pos};
1429
+
1430
+ // The matches method is filled in based on the type of query.
1431
+ // It takes a position and a direction, and returns an object
1432
+ // describing the next occurrence of the query, or null if no
1433
+ // more matches were found.
1434
+ if (typeof query != "string") // Regexp match
1435
+ this.matches = function(reverse, pos) {
1436
+ if (reverse) {
1437
+ var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0;
1438
+ while (match) {
1439
+ var ind = line.indexOf(match[0]);
1440
+ start += ind;
1441
+ line = line.slice(ind + 1);
1442
+ var newmatch = line.match(query);
1443
+ if (newmatch) match = newmatch;
1444
+ else break;
1445
+ start++;
1446
+ }
1447
+ }
1448
+ else {
1449
+ var line = lines[pos.line].text.slice(pos.ch), match = line.match(query),
1450
+ start = match && pos.ch + line.indexOf(match[0]);
1451
+ }
1452
+ if (match)
1453
+ return {from: {line: pos.line, ch: start},
1454
+ to: {line: pos.line, ch: start + match[0].length},
1455
+ match: match};
1456
+ };
1457
+ else { // String query
1458
+ if (caseFold) query = query.toLowerCase();
1459
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
1460
+ var target = query.split("\n");
1461
+ // Different methods for single-line and multi-line queries
1462
+ if (target.length == 1)
1463
+ this.matches = function(reverse, pos) {
1464
+ var line = fold(lines[pos.line].text), len = query.length, match;
1465
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
1466
+ : (match = line.indexOf(query, pos.ch)) != -1)
1467
+ return {from: {line: pos.line, ch: match},
1468
+ to: {line: pos.line, ch: match + len}};
1469
+ };
1470
+ else
1471
+ this.matches = function(reverse, pos) {
1472
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text);
1473
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
1474
+ if (reverse ? offsetA >= pos.ch || offsetA != match.length
1475
+ : offsetA <= pos.ch || offsetA != line.length - match.length)
1476
+ return;
1477
+ for (;;) {
1478
+ if (reverse ? !ln : ln == lines.length - 1) return;
1479
+ line = fold(lines[ln += reverse ? -1 : 1].text);
1480
+ match = target[reverse ? --idx : ++idx];
1481
+ if (idx > 0 && idx < target.length - 1) {
1482
+ if (line != match) return;
1483
+ else continue;
1484
+ }
1485
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
1486
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
1487
+ return;
1488
+ var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
1489
+ return {from: reverse ? end : start, to: reverse ? start : end};
1490
+ }
1491
+ };
1492
+ }
1493
+ }
1494
+
1495
+ SearchCursor.prototype = {
1496
+ findNext: function() {return this.find(false);},
1497
+ findPrevious: function() {return this.find(true);},
1498
+
1499
+ find: function(reverse) {
1500
+ var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to);
1501
+ function savePosAndFail(line) {
1502
+ var pos = {line: line, ch: 0};
1503
+ self.pos = {from: pos, to: pos};
1504
+ self.atOccurrence = false;
1505
+ return false;
1506
+ }
1507
+
1508
+ for (;;) {
1509
+ if (this.pos = this.matches(reverse, pos)) {
1510
+ this.atOccurrence = true;
1511
+ return this.pos.match || true;
1512
+ }
1513
+ if (reverse) {
1514
+ if (!pos.line) return savePosAndFail(0);
1515
+ pos = {line: pos.line-1, ch: lines[pos.line-1].text.length};
1516
+ }
1517
+ else {
1518
+ if (pos.line == lines.length - 1) return savePosAndFail(lines.length);
1519
+ pos = {line: pos.line+1, ch: 0};
1520
+ }
1521
+ }
1522
+ },
1523
+
1524
+ from: function() {if (this.atOccurrence) return copyPos(this.pos.from);},
1525
+ to: function() {if (this.atOccurrence) return copyPos(this.pos.to);},
1526
+
1527
+ replace: function(newText) {
1528
+ var self = this;
1529
+ if (this.atOccurrence)
1530
+ operation(function() {
1531
+ self.pos.to = replaceRange(newText, self.pos.from, self.pos.to);
1532
+ })();
1533
+ }
1534
+ };
1535
+
1536
+ for (var ext in extensions)
1537
+ if (extensions.propertyIsEnumerable(ext) &&
1538
+ !instance.propertyIsEnumerable(ext))
1539
+ instance[ext] = extensions[ext];
1540
+ return instance;
1541
+ } // (end of function CodeMirror)
1542
+
1543
+ // The default configuration options.
1544
+ CodeMirror.defaults = {
1545
+ value: "",
1546
+ mode: null,
1547
+ theme: "default",
1548
+ indentUnit: 2,
1549
+ indentWithTabs: false,
1550
+ tabMode: "classic",
1551
+ enterMode: "indent",
1552
+ electricChars: true,
1553
+ onKeyEvent: null,
1554
+ lineNumbers: false,
1555
+ gutter: false,
1556
+ fixedGutter: false,
1557
+ firstLineNumber: 1,
1558
+ readOnly: false,
1559
+ smartHome: true,
1560
+ onChange: null,
1561
+ onCursorActivity: null,
1562
+ onGutterClick: null,
1563
+ onHighlightComplete: null,
1564
+ onFocus: null, onBlur: null, onScroll: null,
1565
+ matchBrackets: false,
1566
+ workTime: 100,
1567
+ workDelay: 200,
1568
+ undoDepth: 40,
1569
+ tabindex: null,
1570
+ document: window.document
1571
+ };
1572
+
1573
+ // Known modes, by name and by MIME
1574
+ var modes = {}, mimeModes = {};
1575
+ CodeMirror.defineMode = function(name, mode) {
1576
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1577
+ modes[name] = mode;
1578
+ };
1579
+ CodeMirror.defineMIME = function(mime, spec) {
1580
+ mimeModes[mime] = spec;
1581
+ };
1582
+ CodeMirror.getMode = function(options, spec) {
1583
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1584
+ spec = mimeModes[spec];
1585
+ if (typeof spec == "string")
1586
+ var mname = spec, config = {};
1587
+ else if (spec != null)
1588
+ var mname = spec.name, config = spec;
1589
+ var mfactory = modes[mname];
1590
+ if (!mfactory) {
1591
+ if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
1592
+ return CodeMirror.getMode(options, "text/plain");
1593
+ }
1594
+ return mfactory(options, config || {});
1595
+ };
1596
+ CodeMirror.listModes = function() {
1597
+ var list = [];
1598
+ for (var m in modes)
1599
+ if (modes.propertyIsEnumerable(m)) list.push(m);
1600
+ return list;
1601
+ };
1602
+ CodeMirror.listMIMEs = function() {
1603
+ var list = [];
1604
+ for (var m in mimeModes)
1605
+ if (mimeModes.propertyIsEnumerable(m)) list.push(m);
1606
+ return list;
1607
+ };
1608
+
1609
+ var extensions = {};
1610
+ CodeMirror.defineExtension = function(name, func) {
1611
+ extensions[name] = func;
1612
+ };
1613
+
1614
+ CodeMirror.fromTextArea = function(textarea, options) {
1615
+ if (!options) options = {};
1616
+ options.value = textarea.value;
1617
+ if (!options.tabindex && textarea.tabindex)
1618
+ options.tabindex = textarea.tabindex;
1619
+
1620
+ function save() {textarea.value = instance.getValue();}
1621
+ if (textarea.form) {
1622
+ // Deplorable hack to make the submit method do the right thing.
1623
+ var rmSubmit = connect(textarea.form, "submit", save, true);
1624
+ if (typeof textarea.form.submit == "function") {
1625
+ var realSubmit = textarea.form.submit;
1626
+ function wrappedSubmit() {
1627
+ save();
1628
+ textarea.form.submit = realSubmit;
1629
+ textarea.form.submit();
1630
+ textarea.form.submit = wrappedSubmit;
1631
+ }
1632
+ textarea.form.submit = wrappedSubmit;
1633
+ }
1634
+ }
1635
+
1636
+ textarea.style.display = "none";
1637
+ var instance = CodeMirror(function(node) {
1638
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
1639
+ }, options);
1640
+ instance.save = save;
1641
+ instance.toTextArea = function() {
1642
+ save();
1643
+ textarea.parentNode.removeChild(instance.getWrapperElement());
1644
+ textarea.style.display = "";
1645
+ if (textarea.form) {
1646
+ rmSubmit();
1647
+ if (typeof textarea.form.submit == "function")
1648
+ textarea.form.submit = realSubmit;
1649
+ }
1650
+ };
1651
+ return instance;
1652
+ };
1653
+
1654
+ // Utility functions for working with state. Exported because modes
1655
+ // sometimes need to do this.
1656
+ function copyState(mode, state) {
1657
+ if (state === true) return state;
1658
+ if (mode.copyState) return mode.copyState(state);
1659
+ var nstate = {};
1660
+ for (var n in state) {
1661
+ var val = state[n];
1662
+ if (val instanceof Array) val = val.concat([]);
1663
+ nstate[n] = val;
1664
+ }
1665
+ return nstate;
1666
+ }
1667
+ CodeMirror.startState = startState;
1668
+ function startState(mode, a1, a2) {
1669
+ return mode.startState ? mode.startState(a1, a2) : true;
1670
+ }
1671
+ CodeMirror.copyState = copyState;
1672
+
1673
+ // The character stream used by a mode's parser.
1674
+ function StringStream(string) {
1675
+ this.pos = this.start = 0;
1676
+ this.string = string;
1677
+ }
1678
+ StringStream.prototype = {
1679
+ eol: function() {return this.pos >= this.string.length;},
1680
+ sol: function() {return this.pos == 0;},
1681
+ peek: function() {return this.string.charAt(this.pos);},
1682
+ next: function() {
1683
+ if (this.pos < this.string.length)
1684
+ return this.string.charAt(this.pos++);
1685
+ },
1686
+ eat: function(match) {
1687
+ var ch = this.string.charAt(this.pos);
1688
+ if (typeof match == "string") var ok = ch == match;
1689
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
1690
+ if (ok) {++this.pos; return ch;}
1691
+ },
1692
+ eatWhile: function(match) {
1693
+ var start = this.pos;
1694
+ while (this.eat(match)){}
1695
+ return this.pos > start;
1696
+ },
1697
+ eatSpace: function() {
1698
+ var start = this.pos;
1699
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
1700
+ return this.pos > start;
1701
+ },
1702
+ skipToEnd: function() {this.pos = this.string.length;},
1703
+ skipTo: function(ch) {
1704
+ var found = this.string.indexOf(ch, this.pos);
1705
+ if (found > -1) {this.pos = found; return true;}
1706
+ },
1707
+ backUp: function(n) {this.pos -= n;},
1708
+ column: function() {return countColumn(this.string, this.start);},
1709
+ indentation: function() {return countColumn(this.string);},
1710
+ match: function(pattern, consume, caseInsensitive) {
1711
+ if (typeof pattern == "string") {
1712
+ function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
1713
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
1714
+ if (consume !== false) this.pos += pattern.length;
1715
+ return true;
1716
+ }
1717
+ }
1718
+ else {
1719
+ var match = this.string.slice(this.pos).match(pattern);
1720
+ if (match && consume !== false) this.pos += match[0].length;
1721
+ return match;
1722
+ }
1723
+ },
1724
+ current: function(){return this.string.slice(this.start, this.pos);}
1725
+ };
1726
+ CodeMirror.StringStream = StringStream;
1727
+
1728
+ // Line objects. These hold state related to a line, including
1729
+ // highlighting info (the styles array).
1730
+ function Line(text, styles) {
1731
+ this.styles = styles || [text, null];
1732
+ this.stateAfter = null;
1733
+ this.text = text;
1734
+ this.marked = this.gutterMarker = this.className = null;
1735
+ }
1736
+ Line.prototype = {
1737
+ // Replace a piece of a line, keeping the styles around it intact.
1738
+ replace: function(from, to, text) {
1739
+ var st = [], mk = this.marked;
1740
+ copyStyles(0, from, this.styles, st);
1741
+ if (text) st.push(text, null);
1742
+ copyStyles(to, this.text.length, this.styles, st);
1743
+ this.styles = st;
1744
+ this.text = this.text.slice(0, from) + text + this.text.slice(to);
1745
+ this.stateAfter = null;
1746
+ if (mk) {
1747
+ var diff = text.length - (to - from), end = this.text.length;
1748
+ function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;}
1749
+ for (var i = 0; i < mk.length; ++i) {
1750
+ var mark = mk[i], del = false;
1751
+ if (mark.from >= end) del = true;
1752
+ else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);}
1753
+ if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;}
1754
+ }
1755
+ }
1756
+ },
1757
+ // Split a line in two, again keeping styles intact.
1758
+ split: function(pos, textBefore) {
1759
+ var st = [textBefore, null];
1760
+ copyStyles(pos, this.text.length, this.styles, st);
1761
+ return new Line(textBefore + this.text.slice(pos), st);
1762
+ },
1763
+ addMark: function(from, to, style) {
1764
+ var mk = this.marked, mark = {from: from, to: to, style: style};
1765
+ if (this.marked == null) this.marked = [];
1766
+ this.marked.push(mark);
1767
+ this.marked.sort(function(a, b){return a.from - b.from;});
1768
+ return mark;
1769
+ },
1770
+ removeMark: function(mark) {
1771
+ var mk = this.marked;
1772
+ if (!mk) return;
1773
+ for (var i = 0; i < mk.length; ++i)
1774
+ if (mk[i] == mark) {mk.splice(i, 1); break;}
1775
+ },
1776
+ // Run the given mode's parser over a line, update the styles
1777
+ // array, which contains alternating fragments of text and CSS
1778
+ // classes.
1779
+ highlight: function(mode, state) {
1780
+ var stream = new StringStream(this.text), st = this.styles, pos = 0;
1781
+ var changed = false, curWord = st[0], prevWord;
1782
+ if (this.text == "" && mode.blankLine) mode.blankLine(state);
1783
+ while (!stream.eol()) {
1784
+ var style = mode.token(stream, state);
1785
+ var substr = this.text.slice(stream.start, stream.pos);
1786
+ stream.start = stream.pos;
1787
+ if (pos && st[pos-1] == style)
1788
+ st[pos-2] += substr;
1789
+ else if (substr) {
1790
+ if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
1791
+ st[pos++] = substr; st[pos++] = style;
1792
+ prevWord = curWord; curWord = st[pos];
1793
+ }
1794
+ // Give up when line is ridiculously long
1795
+ if (stream.pos > 5000) {
1796
+ st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
1797
+ break;
1798
+ }
1799
+ }
1800
+ if (st.length != pos) {st.length = pos; changed = true;}
1801
+ if (pos && st[pos-2] != prevWord) changed = true;
1802
+ // Short lines with simple highlights return null, and are
1803
+ // counted as changed by the driver because they are likely to
1804
+ // highlight the same way in various contexts.
1805
+ return changed || (st.length < 5 && this.text.length < 10 ? null : false);
1806
+ },
1807
+ // Fetch the parser token for a given character. Useful for hacks
1808
+ // that want to inspect the mode state (say, for completion).
1809
+ getTokenAt: function(mode, state, ch) {
1810
+ var txt = this.text, stream = new StringStream(txt);
1811
+ while (stream.pos < ch && !stream.eol()) {
1812
+ stream.start = stream.pos;
1813
+ var style = mode.token(stream, state);
1814
+ }
1815
+ return {start: stream.start,
1816
+ end: stream.pos,
1817
+ string: stream.current(),
1818
+ className: style || null,
1819
+ state: state};
1820
+ },
1821
+ indentation: function() {return countColumn(this.text);},
1822
+ // Produces an HTML fragment for the line, taking selection,
1823
+ // marking, and highlighting into account.
1824
+ getHTML: function(sfrom, sto, includePre, endAt) {
1825
+ var html = [];
1826
+ if (includePre)
1827
+ html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
1828
+ function span(text, style) {
1829
+ if (!text) return;
1830
+ if (style) html.push('<span class="', style, '">', htmlEscape(text), "</span>");
1831
+ else html.push(htmlEscape(text));
1832
+ }
1833
+ var st = this.styles, allText = this.text, marked = this.marked;
1834
+ if (sfrom == sto) sfrom = null;
1835
+ var len = allText.length;
1836
+ if (endAt != null) len = Math.min(endAt, len);
1837
+
1838
+ if (!allText && endAt == null)
1839
+ span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
1840
+ else if (!marked && sfrom == null)
1841
+ for (var i = 0, ch = 0; ch < len; i+=2) {
1842
+ var str = st[i], l = str.length;
1843
+ if (ch + l > len) str = str.slice(0, len - ch);
1844
+ ch += l;
1845
+ span(str, "cm-" + st[i+1]);
1846
+ }
1847
+ else {
1848
+ var pos = 0, i = 0, text = "", style, sg = 0;
1849
+ var markpos = -1, mark = null;
1850
+ function nextMark() {
1851
+ if (marked) {
1852
+ markpos += 1;
1853
+ mark = (markpos < marked.length) ? marked[markpos] : null;
1854
+ }
1855
+ }
1856
+ nextMark();
1857
+ while (pos < len) {
1858
+ var upto = len;
1859
+ var extraStyle = "";
1860
+ if (sfrom != null) {
1861
+ if (sfrom > pos) upto = sfrom;
1862
+ else if (sto == null || sto > pos) {
1863
+ extraStyle = " CodeMirror-selected";
1864
+ if (sto != null) upto = Math.min(upto, sto);
1865
+ }
1866
+ }
1867
+ while (mark && mark.to != null && mark.to <= pos) nextMark();
1868
+ if (mark) {
1869
+ if (mark.from > pos) upto = Math.min(upto, mark.from);
1870
+ else {
1871
+ extraStyle += " " + mark.style;
1872
+ if (mark.to != null) upto = Math.min(upto, mark.to);
1873
+ }
1874
+ }
1875
+ for (;;) {
1876
+ var end = pos + text.length;
1877
+ var appliedStyle = style;
1878
+ if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle;
1879
+ span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
1880
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
1881
+ pos = end;
1882
+ text = st[i++]; style = "cm-" + st[i++];
1883
+ }
1884
+ }
1885
+ if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
1886
+ }
1887
+ if (includePre) html.push("</pre>");
1888
+ return html.join("");
1889
+ }
1890
+ };
1891
+ // Utility used by replace and split above
1892
+ function copyStyles(from, to, source, dest) {
1893
+ for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
1894
+ var part = source[i], end = pos + part.length;
1895
+ if (state == 0) {
1896
+ if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
1897
+ if (end >= from) state = 1;
1898
+ }
1899
+ else if (state == 1) {
1900
+ if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
1901
+ else dest.push(part, source[i+1]);
1902
+ }
1903
+ pos = end;
1904
+ }
1905
+ }
1906
+
1907
+ // The history object 'chunks' changes that are made close together
1908
+ // and at almost the same time into bigger undoable units.
1909
+ function History() {
1910
+ this.time = 0;
1911
+ this.done = []; this.undone = [];
1912
+ }
1913
+ History.prototype = {
1914
+ addChange: function(start, added, old) {
1915
+ this.undone.length = 0;
1916
+ var time = +new Date, last = this.done[this.done.length - 1];
1917
+ if (time - this.time > 400 || !last ||
1918
+ last.start > start + added || last.start + last.added < start - last.added + last.old.length)
1919
+ this.done.push({start: start, added: added, old: old});
1920
+ else {
1921
+ var oldoff = 0;
1922
+ if (start < last.start) {
1923
+ for (var i = last.start - start - 1; i >= 0; --i)
1924
+ last.old.unshift(old[i]);
1925
+ last.added += last.start - start;
1926
+ last.start = start;
1927
+ }
1928
+ else if (last.start < start) {
1929
+ oldoff = start - last.start;
1930
+ added += oldoff;
1931
+ }
1932
+ for (var i = last.added - oldoff, e = old.length; i < e; ++i)
1933
+ last.old.push(old[i]);
1934
+ if (last.added < added) last.added = added;
1935
+ }
1936
+ this.time = time;
1937
+ }
1938
+ };
1939
+
1940
+ function stopMethod() {e_stop(this);}
1941
+ // Ensure an event has a stop method.
1942
+ function addStop(event) {
1943
+ if (!event.stop) event.stop = stopMethod;
1944
+ return event;
1945
+ }
1946
+
1947
+ function e_preventDefault(e) {
1948
+ if (e.preventDefault) e.preventDefault();
1949
+ else e.returnValue = false;
1950
+ }
1951
+ function e_stopPropagation(e) {
1952
+ if (e.stopPropagation) e.stopPropagation();
1953
+ else e.cancelBubble = true;
1954
+ }
1955
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
1956
+ function e_target(e) {return e.target || e.srcElement;}
1957
+ function e_button(e) {
1958
+ if (e.which) return e.which;
1959
+ else if (e.button & 1) return 1;
1960
+ else if (e.button & 2) return 3;
1961
+ else if (e.button & 4) return 2;
1962
+ }
1963
+
1964
+ // Event handler registration. If disconnect is true, it'll return a
1965
+ // function that unregisters the handler.
1966
+ function connect(node, type, handler, disconnect) {
1967
+ function wrapHandler(event) {handler(event || window.event);}
1968
+ if (typeof node.addEventListener == "function") {
1969
+ node.addEventListener(type, wrapHandler, false);
1970
+ if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);};
1971
+ }
1972
+ else {
1973
+ node.attachEvent("on" + type, wrapHandler);
1974
+ if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
1975
+ }
1976
+ }
1977
+
1978
+ function Delayed() {this.id = null;}
1979
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
1980
+
1981
+ // Some IE versions don't preserve whitespace when setting the
1982
+ // innerHTML of a PRE tag.
1983
+ var badInnerHTML = (function() {
1984
+ var pre = document.createElement("pre");
1985
+ pre.innerHTML = " "; return !pre.innerHTML;
1986
+ })();
1987
+
1988
+ var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
1989
+ var ie = /MSIE \d/.test(navigator.userAgent);
1990
+ var safari = /Apple Computer/.test(navigator.vendor);
1991
+
1992
+ var lineSep = "\n";
1993
+ // Feature-detect whether newlines in textareas are converted to \r\n
1994
+ (function () {
1995
+ var te = document.createElement("textarea");
1996
+ te.value = "foo\nbar";
1997
+ if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
1998
+ }());
1999
+
2000
+ var tabSize = 8;
2001
+ var mac = /Mac/.test(navigator.platform);
2002
+ var movementKeys = {};
2003
+ for (var i = 35; i <= 40; ++i)
2004
+ movementKeys[i] = movementKeys["c" + i] = true;
2005
+
2006
+ // Counts the column offset in a string, taking tabs into account.
2007
+ // Used mostly to find indentation.
2008
+ function countColumn(string, end) {
2009
+ if (end == null) {
2010
+ end = string.search(/[^\s\u00a0]/);
2011
+ if (end == -1) end = string.length;
2012
+ }
2013
+ for (var i = 0, n = 0; i < end; ++i) {
2014
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
2015
+ else ++n;
2016
+ }
2017
+ return n;
2018
+ }
2019
+
2020
+ function computedStyle(elt) {
2021
+ if (elt.currentStyle) return elt.currentStyle;
2022
+ return window.getComputedStyle(elt, null);
2023
+ }
2024
+ // Find the position of an element by following the offsetParent chain.
2025
+ // If screen==true, it returns screen (rather than page) coordinates.
2026
+ function eltOffset(node, screen) {
2027
+ var doc = node.ownerDocument.body;
2028
+ var x = 0, y = 0, skipDoc = false;
2029
+ for (var n = node; n; n = n.offsetParent) {
2030
+ x += n.offsetLeft; y += n.offsetTop;
2031
+ if (screen && computedStyle(n).position == "fixed")
2032
+ skipDoc = true;
2033
+ }
2034
+ var e = screen && !skipDoc ? null : doc;
2035
+ for (var n = node.parentNode; n != e; n = n.parentNode)
2036
+ if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
2037
+ return {left: x, top: y};
2038
+ }
2039
+ // Get a node's text content.
2040
+ function eltText(node) {
2041
+ return node.textContent || node.innerText || node.nodeValue || "";
2042
+ }
2043
+
2044
+ // Operations on {line, ch} objects.
2045
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2046
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2047
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
2048
+
2049
+ var escapeElement = document.createElement("div");
2050
+ function htmlEscape(str) {
2051
+ escapeElement.innerText = escapeElement.textContent = str;
2052
+ return escapeElement.innerHTML;
2053
+ }
2054
+ CodeMirror.htmlEscape = htmlEscape;
2055
+
2056
+ // Used to position the cursor after an undo/redo by finding the
2057
+ // last edited character.
2058
+ function editEnd(from, to) {
2059
+ if (!to) return from ? from.length : 0;
2060
+ if (!from) return to.length;
2061
+ for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
2062
+ if (from.charAt(i) != to.charAt(j)) break;
2063
+ return j + 1;
2064
+ }
2065
+
2066
+ function indexOf(collection, elt) {
2067
+ if (collection.indexOf) return collection.indexOf(elt);
2068
+ for (var i = 0, e = collection.length; i < e; ++i)
2069
+ if (collection[i] == elt) return i;
2070
+ return -1;
2071
+ }
2072
+
2073
+ // See if "".split is the broken IE version, if so, provide an
2074
+ // alternative way to split lines.
2075
+ var splitLines, selRange, setSelRange;
2076
+ if ("\n\nb".split(/\n/).length != 3)
2077
+ splitLines = function(string) {
2078
+ var pos = 0, nl, result = [];
2079
+ while ((nl = string.indexOf("\n", pos)) > -1) {
2080
+ result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
2081
+ pos = nl + 1;
2082
+ }
2083
+ result.push(string.slice(pos));
2084
+ return result;
2085
+ };
2086
+ else
2087
+ splitLines = function(string){return string.split(/\r?\n/);};
2088
+ CodeMirror.splitLines = splitLines;
2089
+
2090
+ // Sane model of finding and setting the selection in a textarea
2091
+ if (window.getSelection) {
2092
+ selRange = function(te) {
2093
+ try {return {start: te.selectionStart, end: te.selectionEnd};}
2094
+ catch(e) {return null;}
2095
+ };
2096
+ if (safari)
2097
+ // On Safari, selection set with setSelectionRange are in a sort
2098
+ // of limbo wrt their anchor. If you press shift-left in them,
2099
+ // the anchor is put at the end, and the selection expanded to
2100
+ // the left. If you press shift-right, the anchor ends up at the
2101
+ // front. This is not what CodeMirror wants, so it does a
2102
+ // spurious modify() call to get out of limbo.
2103
+ setSelRange = function(te, start, end) {
2104
+ if (start == end)
2105
+ te.setSelectionRange(start, end);
2106
+ else {
2107
+ te.setSelectionRange(start, end - 1);
2108
+ window.getSelection().modify("extend", "forward", "character");
2109
+ }
2110
+ };
2111
+ else
2112
+ setSelRange = function(te, start, end) {
2113
+ try {te.setSelectionRange(start, end);}
2114
+ catch(e) {} // Fails on Firefox when textarea isn't part of the document
2115
+ };
2116
+ }
2117
+ // IE model. Don't ask.
2118
+ else {
2119
+ selRange = function(te) {
2120
+ try {var range = te.ownerDocument.selection.createRange();}
2121
+ catch(e) {return null;}
2122
+ if (!range || range.parentElement() != te) return null;
2123
+ var val = te.value, len = val.length, localRange = te.createTextRange();
2124
+ localRange.moveToBookmark(range.getBookmark());
2125
+ var endRange = te.createTextRange();
2126
+ endRange.collapse(false);
2127
+
2128
+ if (localRange.compareEndPoints("StartToEnd", endRange) > -1)
2129
+ return {start: len, end: len};
2130
+
2131
+ var start = -localRange.moveStart("character", -len);
2132
+ for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {}
2133
+
2134
+ if (localRange.compareEndPoints("EndToEnd", endRange) > -1)
2135
+ return {start: start, end: len};
2136
+
2137
+ var end = -localRange.moveEnd("character", -len);
2138
+ for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {}
2139
+ return {start: start, end: end};
2140
+ };
2141
+ setSelRange = function(te, start, end) {
2142
+ var range = te.createTextRange();
2143
+ range.collapse(true);
2144
+ var endrange = range.duplicate();
2145
+ var newlines = 0, txt = te.value;
2146
+ for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1))
2147
+ ++newlines;
2148
+ range.move("character", start - newlines);
2149
+ for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1))
2150
+ ++newlines;
2151
+ endrange.move("character", end - newlines);
2152
+ range.setEndPoint("EndToEnd", endrange);
2153
+ range.select();
2154
+ };
2155
+ }
2156
+
2157
+ CodeMirror.defineMode("null", function() {
2158
+ return {token: function(stream) {stream.skipToEnd();}};
2159
+ });
2160
+ CodeMirror.defineMIME("text/plain", "null");
2161
+
2162
+ return CodeMirror;
2163
+ })()
2164
+ ;