Nowa wersja CodeMirror.
[redakcja.git] / project / static / js / lib / codemirror / codemirror.js
1 /* CodeMirror main module
2  *
3  * Implements the CodeMirror constructor and prototype, which take care
4  * of initializing the editor frame, and providing the outside interface.
5  */
6
7 // The CodeMirrorConfig object is used to specify a default
8 // configuration. If you specify such an object before loading this
9 // file, the values you put into it will override the defaults given
10 // below. You can also assign to it after loading.
11 var CodeMirrorConfig = window.CodeMirrorConfig || {};
12
13 var CodeMirror = (function(){
14   function setDefaults(object, defaults) {
15     for (var option in defaults) {
16       if (!object.hasOwnProperty(option))
17         object[option] = defaults[option];
18     }
19   }
20   function forEach(array, action) {
21     for (var i = 0; i < array.length; i++)
22       action(array[i]);
23   }
24
25   // These default options can be overridden by passing a set of
26   // options to a specific CodeMirror constructor. See manual.html for
27   // their meaning.
28   setDefaults(CodeMirrorConfig, {
29     stylesheet: "",
30     path: "",
31     parserfile: [],
32     basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
33     iframeClass: null,
34     passDelay: 200,
35     passTime: 50,
36     continuousScanning: false,
37     saveFunction: null,
38     onChange: null,
39     undoDepth: 50,
40     undoDelay: 800,
41     disableSpellcheck: true,
42     textWrapping: true,
43     readOnly: false,
44     width: "100%",
45     height: "300px",
46     autoMatchParens: false,
47     parserConfig: null,
48     tabMode: "indent", // or "spaces", "default", "shift"
49     reindentOnLoad: false,
50     activeTokens: null,
51     cursorActivity: null,
52     lineNumbers: false,
53     indentUnit: 2
54   });
55
56   function wrapLineNumberDiv(place) {
57     return function(node) {
58       var container = document.createElement("DIV"),
59           nums = document.createElement("DIV"),
60           scroller = document.createElement("DIV");
61       container.style.position = "relative";
62       nums.style.position = "absolute";
63       nums.style.height = "100%";
64       if (nums.style.setExpression) {
65         try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");}
66         catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions
67       }
68       nums.style.top = "0px";
69       nums.style.overflow = "hidden";
70       place(container);
71       container.appendChild(node);
72       container.appendChild(nums);
73       scroller.className = "CodeMirror-line-numbers";
74       nums.appendChild(scroller);
75     }
76   }
77
78   function applyLineNumbers(frame) {
79     var win = frame.contentWindow, doc = win.document,
80         nums = frame.nextSibling, scroller = nums.firstChild;
81
82     var nextNum = 1, barWidth = null;
83     function sizeBar() {
84       for (var root = frame; root.parentNode; root = root.parentNode);
85       if (root != document || !win.Editor) {
86         clearInterval(sizeInterval);
87         return;
88       }
89
90       if (nums.offsetWidth != barWidth) {
91         barWidth = nums.offsetWidth;
92         nums.style.left = "-" + (frame.parentNode.style.marginLeft = barWidth + "px");
93       }
94     }
95     function update() {
96       var diff = 20 + Math.max(doc.body.offsetHeight, frame.offsetHeight) - scroller.offsetHeight;
97       for (var n = Math.ceil(diff / 10); n > 0; n--) {
98         var div = document.createElement("DIV");
99         div.appendChild(document.createTextNode(nextNum++));
100         scroller.appendChild(div);
101       }
102       nums.scrollTop = doc.body.scrollTop || doc.documentElement.scrollTop || 0;
103     }
104     sizeBar();
105     update();
106     win.addEventHandler(win, "scroll", update);
107     win.addEventHandler(win, "resize", update);
108     var sizeInterval = setInterval(sizeBar, 500);
109   }
110
111   function CodeMirror(place, options) {
112     // Backward compatibility for deprecated options.
113     if (options.dumbTabs) options.tabMode = "spaces";
114     else if (options.normalTab) options.tabMode = "default";
115
116     // Use passed options, if any, to override defaults.
117     this.options = options = options || {};
118     setDefaults(options, CodeMirrorConfig);
119
120     var frame = this.frame = document.createElement("IFRAME");
121     if (options.iframeClass) frame.className = options.iframeClass;
122     frame.frameBorder = 0;
123     frame.src = "javascript:false;";
124     frame.style.border = "0";
125     frame.style.width = options.width;
126     frame.style.height = options.height;
127     // display: block occasionally suppresses some Firefox bugs, so we
128     // always add it, redundant as it sounds.
129     frame.style.display = "block";
130
131     if (place.appendChild) {
132       var node = place;
133       place = function(n){node.appendChild(n);};
134     }
135     if (options.lineNumbers) place = wrapLineNumberDiv(place);
136     place(frame);
137
138     // Link back to this object, so that the editor can fetch options
139     // and add a reference to itself.
140     frame.CodeMirror = this;
141     this.win = frame.contentWindow;
142
143     if (typeof options.parserfile == "string")
144       options.parserfile = [options.parserfile];
145     if (typeof options.stylesheet == "string")
146       options.stylesheet = [options.stylesheet];
147
148     var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];
149     // Hack to work around a bunch of IE8-specific problems.
150     html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
151     forEach(options.stylesheet, function(file) {
152       html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
153     });
154     forEach(options.basefiles.concat(options.parserfile), function(file) {
155       html.push("<script type=\"text/javascript\" src=\"" + options.path + file + "\"></script>");
156     });
157     html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
158               (options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
159
160     var doc = this.win.document;
161     doc.open();
162     doc.write(html.join(""));
163     doc.close();
164   }
165
166   CodeMirror.prototype = {
167     init: function() {
168       if (this.options.initCallback) this.options.initCallback(this);
169       if (this.options.lineNumbers) applyLineNumbers(this.frame);
170       if (this.options.reindentOnLoad) this.reindent();
171     },
172
173     getCode: function() {return this.editor.getCode();},
174     setCode: function(code) {this.editor.importCode(code);},
175     selection: function() {this.focusIfIE(); return this.editor.selectedText();},
176     reindent: function() {this.editor.reindent();},
177     reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);},
178
179     focusIfIE: function() {
180       // in IE, a lot of selection-related functionality only works when the frame is focused
181       if (this.win.select.ie_selection) this.focus();
182     },
183     focus: function() {
184       this.win.focus();
185       if (this.editor.selectionSnapshot) // IE hack
186         this.win.select.selectCoords(this.win, this.editor.selectionSnapshot);
187     },
188     replaceSelection: function(text) {
189       this.focus();
190       this.editor.replaceSelection(text);
191       return true;
192     },
193     replaceChars: function(text, start, end) {
194       this.editor.replaceChars(text, start, end);
195     },
196     getSearchCursor: function(string, fromCursor) {
197       return this.editor.getSearchCursor(string, fromCursor);
198     },
199
200     undo: function() {this.editor.history.undo();},
201     redo: function() {this.editor.history.redo();},
202     historySize: function() {return this.editor.history.historySize();},
203     clearHistory: function() {this.editor.history.clear();},
204
205     grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);},
206     ungrabKeys: function() {this.editor.ungrabKeys();},
207
208     setParser: function(name) {this.editor.setParser(name);},
209
210     cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);},
211     firstLine: function() {return this.editor.firstLine();},
212     lastLine: function() {return this.editor.lastLine();},
213     nextLine: function(line) {return this.editor.nextLine(line);},
214     prevLine: function(line) {return this.editor.prevLine(line);},
215     lineContent: function(line) {return this.editor.lineContent(line);},
216     setLineContent: function(line, content) {this.editor.setLineContent(line, content);},
217     insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);},
218     selectLines: function(startLine, startOffset, endLine, endOffset) {
219       this.win.focus();
220       this.editor.selectLines(startLine, startOffset, endLine, endOffset);
221     },
222     nthLine: function(n) {
223       var line = this.firstLine();
224       for (; n > 1 && line !== false; n--)
225         line = this.nextLine(line);
226       return line;
227     },
228     lineNumber: function(line) {
229       var num = 0;
230       while (line !== false) {
231         num++;
232         line = this.prevLine(line);
233       }
234       return num;
235     },
236
237     // Old number-based line interface
238     jumpToLine: function(n) {
239       this.selectLines(this.nthLine(n), 0);
240       this.win.focus();
241     },
242     currentLine: function() {
243       return this.lineNumber(this.cursorPosition().line);
244     }
245   };
246
247   CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}};
248
249   CodeMirror.replace = function(element) {
250     if (typeof element == "string")
251       element = document.getElementById(element);
252     return function(newElement) {
253       element.parentNode.replaceChild(newElement, element);
254     };
255   };
256
257   CodeMirror.fromTextArea = function(area, options) {
258     if (typeof area == "string")
259       area = document.getElementById(area);
260
261     options = options || {};
262     if (area.style.width && options.width == null)
263       options.width = area.style.width;
264     if (area.style.height && options.height == null)
265       options.height = area.style.height;
266     if (options.content == null) options.content = area.value;
267
268     if (area.form) {
269       function updateField() {
270         area.value = mirror.getCode();
271       }
272       if (typeof area.form.addEventListener == "function")
273         area.form.addEventListener("submit", updateField, false);
274       else
275         area.form.attachEvent("onsubmit", updateField);
276     }
277
278     function insert(frame) {
279       if (area.nextSibling)
280         area.parentNode.insertBefore(frame, area.nextSibling);
281       else
282         area.parentNode.appendChild(frame);
283     }
284
285     area.style.display = "none";
286     var mirror = new CodeMirror(insert, options);
287     return mirror;
288   };
289
290   CodeMirror.isProbablySupported = function() {
291     // This is rather awful, but can be useful.
292     var match;
293     if (window.opera)
294       return Number(window.opera.version()) >= 9.52;
295     else if (/Apple Computers, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
296       return Number(match[1]) >= 3;
297     else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
298       return Number(match[1]) >= 6;
299     else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
300       return Number(match[1]) >= 20050901;
301     else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/))
302       return Number(match[1]) >= 525;
303     else
304       return null;
305   };
306
307   return CodeMirror;
308 })();