Simpler deployment.
[redakcja.git] / redakcja / 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;
83
84     function update() {
85       var diff = 20 + Math.max(doc.body.offsetHeight, frame.offsetHeight) - scroller.offsetHeight;
86       for (var n = Math.ceil(diff / 10); n > 0; n--) {
87         var div = document.createElement("div");
88         div.appendChild(document.createTextNode(nextNum++));
89         scroller.appendChild(div);
90       }
91       nums.scrollTop = doc.body.scrollTop || doc.documentElement.scrollTop || 0;
92     }
93
94     update();
95     win.addEventHandler(win, "scroll", update);
96     win.addEventHandler(win, "resize", update);
97   }
98
99   function CodeMirror(place, options) {
100     // Backward compatibility for deprecated options.
101     if (options.dumbTabs) options.tabMode = "spaces";
102     else if (options.normalTab) options.tabMode = "default";
103
104     // Use passed options, if any, to override defaults.
105     this.options = options = options || {};
106     setDefaults(options, CodeMirrorConfig);
107
108     var frame = this.frame = document.createElement("iframe");
109     if (options.iframeClass) frame.className = options.iframeClass;
110     frame.frameBorder = 0;
111     frame.src = "javascript:false;";
112     frame.style.border = "0";
113     frame.style.width = options.width;
114     frame.style.height = options.height;
115     // display: block occasionally suppresses some Firefox bugs, so we
116     // always add it, redundant as it sounds.
117     frame.style.display = "block";
118
119     if (place.appendChild) {
120       var node = place;
121       place = function(n){node.appendChild(n);};
122     }
123     if (options.lineNumbers) place = wrapLineNumberDiv(place);
124     place(frame);
125
126     // Link back to this object, so that the editor can fetch options
127     // and add a reference to itself.
128     frame.CodeMirror = this;
129     this.win = frame.contentWindow;
130
131     if (typeof options.parserfile == "string")
132       options.parserfile = [options.parserfile];
133     if (typeof options.stylesheet == "string")
134       options.stylesheet = [options.stylesheet];
135
136     var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];
137     // Hack to work around a bunch of IE8-specific problems.
138     html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
139     forEach(options.stylesheet, function(file) {
140       html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
141     });
142     forEach(options.basefiles.concat(options.parserfile), function(file) {
143       html.push("<script type=\"text/javascript\" src=\"" + options.path + file + "\"></script>");
144     });
145     html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
146               (options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
147
148     var doc = this.win.document;
149     doc.open();
150     doc.write(html.join(""));
151     doc.close();
152   }
153
154   CodeMirror.prototype = {
155     init: function() {
156       if (this.options.initCallback) this.options.initCallback(this);
157       if (this.options.lineNumbers) applyLineNumbers(this.frame);
158       if (this.options.reindentOnLoad) this.reindent();
159     },
160
161     getCode: function() {return this.editor.getCode();},
162     setCode: function(code) {this.editor.importCode(code);},
163     selection: function() {return this.editor.selectedText();},
164     reindent: function() {this.editor.reindent();},
165     reindentSelection: function() {this.editor.reindentSelection(null);},
166
167     focus: function() {
168       this.win.focus();
169       if (this.editor.selectionSnapshot) // IE hack
170         this.win.select.selectCoords(this.win, this.editor.selectionSnapshot);
171     },
172     replaceSelection: function(text) {
173       this.focus();
174       this.editor.replaceSelection(text);
175       return true;
176     },
177     replaceChars: function(text, start, end) {
178       this.editor.replaceChars(text, start, end);
179     },
180     getSearchCursor: function(string, fromCursor) {
181       return this.editor.getSearchCursor(string, fromCursor);
182     },
183
184     undo: function() {this.editor.history.undo();},
185     redo: function() {this.editor.history.redo();},
186     historySize: function() {return this.editor.history.historySize();},
187     clearHistory: function() {this.editor.history.clear();},
188
189     grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);},
190     ungrabKeys: function() {this.editor.ungrabKeys();},
191
192     setParser: function(name) {this.editor.setParser(name);},
193
194     cursorPosition: function(start) {
195       if (this.win.select.ie_selection) this.focus();
196       return this.editor.cursorPosition(start);
197     },
198     firstLine: function() {return this.editor.firstLine();},
199     lastLine: function() {return this.editor.lastLine();},
200     nextLine: function(line) {return this.editor.nextLine(line);},
201     prevLine: function(line) {return this.editor.prevLine(line);},
202     lineContent: function(line) {return this.editor.lineContent(line);},
203     setLineContent: function(line, content) {this.editor.setLineContent(line, content);},
204     insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);},
205     selectLines: function(startLine, startOffset, endLine, endOffset) {
206       this.win.focus();
207       this.editor.selectLines(startLine, startOffset, endLine, endOffset);
208     },
209     nthLine: function(n) {
210       var line = this.firstLine();
211       for (; n > 1 && line !== false; n--)
212         line = this.nextLine(line);
213       return line;
214     },
215     lineNumber: function(line) {
216       var num = 0;
217       while (line !== false) {
218         num++;
219         line = this.prevLine(line);
220       }
221       return num;
222     },
223
224     // Old number-based line interface
225     jumpToLine: function(n) {
226       this.selectLines(this.nthLine(n), 0);
227       this.win.focus();
228     },
229     currentLine: function() {
230       return this.lineNumber(this.cursorPosition().line);
231     }
232   };
233
234   CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}};
235
236   CodeMirror.replace = function(element) {
237     if (typeof element == "string")
238       element = document.getElementById(element);
239     return function(newElement) {
240       element.parentNode.replaceChild(newElement, element);
241     };
242   };
243
244   CodeMirror.fromTextArea = function(area, options) {
245     if (typeof area == "string")
246       area = document.getElementById(area);
247
248     options = options || {};
249     if (area.style.width && options.width == null)
250       options.width = area.style.width;
251     if (area.style.height && options.height == null)
252       options.height = area.style.height;
253     if (options.content == null) options.content = area.value;
254
255     if (area.form) {
256       function updateField() {
257         area.value = mirror.getCode();
258       }
259       if (typeof area.form.addEventListener == "function")
260         area.form.addEventListener("submit", updateField, false);
261       else
262         area.form.attachEvent("onsubmit", updateField);
263     }
264
265     function insert(frame) {
266       if (area.nextSibling)
267         area.parentNode.insertBefore(frame, area.nextSibling);
268       else
269         area.parentNode.appendChild(frame);
270     }
271
272     area.style.display = "none";
273     var mirror = new CodeMirror(insert, options);
274     return mirror;
275   };
276
277   CodeMirror.isProbablySupported = function() {
278     // This is rather awful, but can be useful.
279     var match;
280     if (window.opera)
281       return Number(window.opera.version()) >= 9.52;
282     else if (/Apple Computers, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
283       return Number(match[1]) >= 3;
284     else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
285       return Number(match[1]) >= 6;
286     else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
287       return Number(match[1]) >= 20050901;
288     else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/))
289       return Number(match[1]) >= 525;
290     else
291       return null;
292   };
293
294   return CodeMirror;
295 })();