-
diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx
index 9942fe9498..4e96930591 100644
--- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx
+++ b/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx
@@ -33,7 +33,7 @@
var codeVal = jQuery('#<%= editorSource.ClientID %>').val();
//if CodeMirror is not defined, then the code editor is disabled.
if (typeof (CodeMirror) != "undefined") {
- codeVal = codeEditor.getCode();
+ codeVal = UmbEditor.GetCode();
}
umbraco.presentation.webservices.codeEditorSave.SaveXslt(jQuery('#<%= xsltFileName.ClientID %>').val(), '<%= xsltFileName.Text %>', codeVal, document.getElementById('<%= SkipTesting.ClientID %>').checked, submitSucces, submitFailure);
@@ -55,7 +55,6 @@
function xsltVisualize() {
-
xsltSnippet = UmbEditor.IsSimpleEditor
? jQuery("#<%= editorSource.ClientID %>").getSelection().text
: UmbEditor._editor.selection();
@@ -63,7 +62,7 @@
if (xsltSnippet == '') {
xsltSnippet = UmbEditor.IsSimpleEditor
? jQuery("#<%= editorSource.ClientID %>").val()
- : UmbEditor._editor.getCode();
+ : UmbEditor.GetCode();
// alert('Please select the xslt to visualize');
}
diff --git a/src/Umbraco.Web.UI/umbraco/settings/editTemplate.aspx b/src/Umbraco.Web.UI/umbraco/settings/editTemplate.aspx
index 10abd19469..98050220f9 100644
--- a/src/Umbraco.Web.UI/umbraco/settings/editTemplate.aspx
+++ b/src/Umbraco.Web.UI/umbraco/settings/editTemplate.aspx
@@ -180,8 +180,8 @@
-
+
diff --git a/src/Umbraco.Web.UI/umbraco/settings/scripts/editScript.aspx b/src/Umbraco.Web.UI/umbraco/settings/scripts/editScript.aspx
index 8d3e1b083c..43bb2c05c0 100644
--- a/src/Umbraco.Web.UI/umbraco/settings/scripts/editScript.aspx
+++ b/src/Umbraco.Web.UI/umbraco/settings/scripts/editScript.aspx
@@ -10,7 +10,7 @@
var codeVal = jQuery('#<%= editorSource.ClientID %>').val();
//if CodeMirror is not defined, then the code editor is disabled.
if (typeof (CodeMirror) != "undefined") {
- codeVal = codeEditor.getCode();
+ codeVal = UmbEditor.GetCode();
}
umbraco.presentation.webservices.codeEditorSave.SaveScript(jQuery('#<%= NameTxt.ClientID %>').val(), '<%= NameTxt.Text %>', codeVal, submitSucces, submitFailure);
}
diff --git a/src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx b/src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx
index 3db465356d..fdff83a661 100644
--- a/src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx
+++ b/src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx
@@ -9,7 +9,7 @@
var codeVal = jQuery('#<%= editorSource.ClientID %>').val();
//if CodeMirror is not defined, then the code editor is disabled.
if (typeof(CodeMirror) != "undefined") {
- codeVal = codeEditor.getCode();
+ codeVal = UmbEditor.GetCode();
}
umbraco.presentation.webservices.codeEditorSave.SaveCss(jQuery('#<%= NameTxt.ClientID %>').val(), '<%= NameTxt.Text %>', codeVal, '<%= Request.QueryString["id"] %>', submitSucces, submitFailure);
}
diff --git a/src/Umbraco.Web.UI/umbraco/umbraco.aspx b/src/Umbraco.Web.UI/umbraco/umbraco.aspx
index 9418f921a1..1ac457cf16 100644
--- a/src/Umbraco.Web.UI/umbraco/umbraco.aspx
+++ b/src/Umbraco.Web.UI/umbraco/umbraco.aspx
@@ -10,6 +10,7 @@
Umbraco CMS -
<%=Request.Url.Host.ToLower().Replace("www.", "") %>
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeArea/UmbracoEditor.js b/src/Umbraco.Web.UI/umbraco_client/CodeArea/UmbracoEditor.js
index 229849413e..448ba1bb40 100644
--- a/src/Umbraco.Web.UI/umbraco_client/CodeArea/UmbracoEditor.js
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeArea/UmbracoEditor.js
@@ -10,7 +10,7 @@ Umbraco.Sys.registerNamespace("Umbraco.Controls.CodeEditor");
var _controlId = controlId;
if (!_isSimpleEditor && typeof(codeEditor) == "undefined") {
- throw "CodeMirror editor not found!";
+ throw "CodeMirror editor not found!";
}
//create the inner object
@@ -28,7 +28,7 @@ Umbraco.Sys.registerNamespace("Umbraco.Controls.CodeEditor");
}
else {
//this is a wrapper for CodeMirror
- return this._editor.getCode();
+ return this._editor.getValue();
}
},
SetCode: function(code) {
@@ -37,7 +37,7 @@ Umbraco.Sys.registerNamespace("Umbraco.Controls.CodeEditor");
}
else {
//this is a wrapper for CodeMirror
- this._editor.setCode(code);
+ this._editor.setValue(code);
}
},
Insert: function(open, end, txtEl, arg3) {
@@ -59,14 +59,15 @@ Umbraco.Sys.registerNamespace("Umbraco.Controls.CodeEditor");
}
}
else {
- this._editor.win.document.body.focus(); //need to restore the focus to the editor body
+ this._editor.focus(); //need to restore the focus to the editor body
//if the saved selection (IE only) is not null, then
if (this._cmSave != null) {
this._editor.selectLines(this._cmSave.start.line, this._cmSave.start.character, this._cmSave.end.line, this._cmSave.end.character);
}
- var selection = this._editor.selection();
+ var selection = this._editor.getSelection();
+
var replace = (arg3) ? open + arg3 : open; //concat open and arg3, if arg3 specified
if (end != "") {
replace = replace + selection + end;
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeArea/javascript.js b/src/Umbraco.Web.UI/umbraco_client/CodeArea/javascript.js
index 2d7f547015..9b5c0e4402 100644
--- a/src/Umbraco.Web.UI/umbraco_client/CodeArea/javascript.js
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeArea/javascript.js
@@ -3,11 +3,26 @@ function resizeTextArea(textEditor, offsetX, offsetY) {
var clientWidth = getViewportWidth();
if (textEditor != null) {
- textEditor.style.width = (clientWidth - offsetX) + "px";
+ // textEditor.style.width = (clientWidth - offsetX) + "px";
textEditor.style.height = (clientHeight - getY(textEditor) - offsetY) + "px";
}
}
+var currentHandle = null, currentLine;
+function updateLineInfo(cm) {
+ var line = cm.getCursor().line, handle = cm.getLineHandle(line);
+ if (handle == currentHandle && line == currentLine) return;
+
+ if (currentHandle) {
+ cm.setLineClass(currentHandle, null, null);
+ cm.clearMarker(currentHandle);
+ }
+ currentHandle = handle; currentLine = line;
+ cm.setLineClass(currentHandle, null, "activeline");
+ cm.setMarker(currentHandle, String(line + 1));
+}
+
+
function UmbracoCodeSnippet() {
this.BeginTag = "";
this.EndTag = "";
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeArea/styles.css b/src/Umbraco.Web.UI/umbraco_client/CodeArea/styles.css
index d5ffca6478..ac7074f6a2 100644
--- a/src/Umbraco.Web.UI/umbraco_client/CodeArea/styles.css
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeArea/styles.css
@@ -1,14 +1,10 @@
-.CodeMirror-line-numbers
-{
- color:black;
- background-color:#fff;
- font-family:monospace;
- font-size:10pt;
- padding:6px 6px 0px 0px;
- line-height:16px;
- text-align:right;
- border-right: 1px solid #efefef;
-}
-
-div.codepress{border: none !Important; background: #fff;}
-div.codepress iframe{border: none !Important; background: #fff;}
\ No newline at end of file
+ .CodeMirror {
+ border: none !Important;
+ font-size: 14px !Important;
+ }
+
+ .CodeMirror-gutter{background: none !Important; border: none; padding-rigth: 5px;}
+
+ span.cm-at{background: yellow !Important;}
+
+ textarea.codepress{display: block; width: 100% !Important; font-size: 14px;}
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/CoreCombined.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/CoreCombined.js
deleted file mode 100644
index 06a3e2b8f3..0000000000
--- a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/CoreCombined.js
+++ /dev/null
@@ -1,2687 +0,0 @@
-/* A few useful utility functions. */
-
-var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
-var webkit = /AppleWebKit/.test(navigator.userAgent);
-var safari = /Apple Computers, Inc/.test(navigator.vendor);
-
-// Capture a method on an object.
-function method(obj, name) {
- return function() {obj[name].apply(obj, arguments);};
-}
-
-// The value used to signal the end of a sequence in iterators.
-var StopIteration = {toString: function() {return "StopIteration"}};
-
-// Apply a function to each element in a sequence.
-function forEach(iter, f) {
- if (iter.next) {
- try {while (true) f(iter.next());}
- catch (e) {if (e != StopIteration) throw e;}
- }
- else {
- for (var i = 0; i < iter.length; i++)
- f(iter[i]);
- }
-}
-
-// Map a function over a sequence, producing an array of results.
-function map(iter, f) {
- var accum = [];
- forEach(iter, function(val) {accum.push(f(val));});
- return accum;
-}
-
-// Create a predicate function that tests a string againsts a given
-// regular expression. No longer used but might be used by 3rd party
-// parsers.
-function matcher(regexp){
- return function(value){return regexp.test(value);};
-}
-
-// Test whether a DOM node has a certain CSS class. Much faster than
-// the MochiKit equivalent, for some reason.
-function hasClass(element, className){
- var classes = element.className;
- return classes && new RegExp("(^| )" + className + "($| )").test(classes);
-}
-
-// Insert a DOM node after another node.
-function insertAfter(newNode, oldNode) {
- var parent = oldNode.parentNode;
- parent.insertBefore(newNode, oldNode.nextSibling);
- return newNode;
-}
-
-function removeElement(node) {
- if (node.parentNode)
- node.parentNode.removeChild(node);
-}
-
-function clearElement(node) {
- while (node.firstChild)
- node.removeChild(node.firstChild);
-}
-
-// Check whether a node is contained in another one.
-function isAncestor(node, child) {
- while (child = child.parentNode) {
- if (node == child)
- return true;
- }
- return false;
-}
-
-// The non-breaking space character.
-var nbsp = "\u00a0";
-var matching = {"{": "}", "[": "]", "(": ")",
- "}": "{", "]": "[", ")": "("};
-
-// Standardize a few unportable event properties.
-function normalizeEvent(event) {
- if (!event.stopPropagation) {
- event.stopPropagation = function() {this.cancelBubble = true;};
- event.preventDefault = function() {this.returnValue = false;};
- }
- if (!event.stop) {
- event.stop = function() {
- this.stopPropagation();
- this.preventDefault();
- };
- }
-
- if (event.type == "keypress") {
- event.code = (event.charCode == null) ? event.keyCode : event.charCode;
- event.character = String.fromCharCode(event.code);
- }
- return event;
-}
-
-// Portably register event handlers.
-function addEventHandler(node, type, handler, removeFunc) {
- function wrapHandler(event) {
- handler(normalizeEvent(event || window.event));
- }
- if (typeof node.addEventListener == "function") {
- node.addEventListener(type, wrapHandler, false);
- if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);};
- }
- else {
- node.attachEvent("on" + type, wrapHandler);
- if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);};
- }
-}
-
-function nodeText(node) {
- return node.textContent || node.innerText || node.nodeValue || "";
-}
-
-function nodeTop(node) {
- var top = 0;
- while (node.offsetParent) {
- top += node.offsetTop;
- node = node.offsetParent;
- }
- return top;
-}
-
-function isBR(node) {
- var nn = node.nodeName;
- return nn == "BR" || nn == "br";
-}
-function isSpan(node) {
- var nn = node.nodeName;
- return nn == "SPAN" || nn == "span";
-}
-
-;;;;;
-
-/* String streams are the things fed to parsers (which can feed them
- * to a tokenizer if they want). They provide peek and next methods
- * for looking at the current character (next 'consumes' this
- * character, peek does not), and a get method for retrieving all the
- * text that was consumed since the last time get was called.
- *
- * An easy mistake to make is to let a StopIteration exception finish
- * the token stream while there are still characters pending in the
- * string stream (hitting the end of the buffer while parsing a
- * token). To make it easier to detect such errors, the stringstreams
- * throw an exception when this happens.
- */
-
-// Make a stringstream stream out of an iterator that returns strings.
-// This is applied to the result of traverseDOM (see codemirror.js),
-// and the resulting stream is fed to the parser.
-window.stringStream = function(source){
- // String that's currently being iterated over.
- var current = "";
- // Position in that string.
- var pos = 0;
- // Accumulator for strings that have been iterated over but not
- // get()-ed yet.
- var accum = "";
- // Make sure there are more characters ready, or throw
- // StopIteration.
- function ensureChars() {
- while (pos == current.length) {
- accum += current;
- current = ""; // In case source.next() throws
- pos = 0;
- try {current = source.next();}
- catch (e) {
- if (e != StopIteration) throw e;
- else return false;
- }
- }
- return true;
- }
-
- return {
- // Return the next character in the stream.
- peek: function() {
- if (!ensureChars()) return null;
- return current.charAt(pos);
- },
- // Get the next character, throw StopIteration if at end, check
- // for unused content.
- next: function() {
- if (!ensureChars()) {
- if (accum.length > 0)
- throw "End of stringstream reached without emptying buffer ('" + accum + "').";
- else
- throw StopIteration;
- }
- return current.charAt(pos++);
- },
- // Return the characters iterated over since the last call to
- // .get().
- get: function() {
- var temp = accum;
- accum = "";
- if (pos > 0){
- temp += current.slice(0, pos);
- current = current.slice(pos);
- pos = 0;
- }
- return temp;
- },
- // Push a string back into the stream.
- push: function(str) {
- current = current.slice(0, pos) + str + current.slice(pos);
- },
- lookAhead: function(str, consume, skipSpaces, caseInsensitive) {
- function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
- str = cased(str);
- var found = false;
-
- var _accum = accum, _pos = pos;
- if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/);
-
- while (true) {
- var end = pos + str.length, left = current.length - pos;
- if (end <= current.length) {
- found = str == cased(current.slice(pos, end));
- pos = end;
- break;
- }
- else if (str.slice(0, left) == cased(current.slice(pos))) {
- accum += current; current = "";
- try {current = source.next();}
- catch (e) {break;}
- pos = 0;
- str = str.slice(left);
- }
- else {
- break;
- }
- }
-
- if (!(found && consume)) {
- current = accum.slice(_accum.length) + current;
- pos = _pos;
- accum = _accum;
- }
-
- return found;
- },
-
- // Utils built on top of the above
- more: function() {
- return this.peek() !== null;
- },
- applies: function(test) {
- var next = this.peek();
- return (next !== null && test(next));
- },
- nextWhile: function(test) {
- var next;
- while ((next = this.peek()) !== null && test(next))
- this.next();
- },
- matches: function(re) {
- var next = this.peek();
- return (next !== null && re.test(next));
- },
- nextWhileMatches: function(re) {
- var next;
- while ((next = this.peek()) !== null && re.test(next))
- this.next();
- },
- equals: function(ch) {
- return ch === this.peek();
- },
- endOfLine: function() {
- var next = this.peek();
- return next == null || next == "\n";
- }
- };
-};
-
-;;;;;
-
-/* Functionality for finding, storing, and restoring selections
- *
- * This does not provide a generic API, just the minimal functionality
- * required by the CodeMirror system.
- */
-
-// Namespace object.
-var select = {};
-
-(function() {
- select.ie_selection = document.selection && document.selection.createRangeCollection;
-
- // Find the 'top-level' (defined as 'a direct child of the node
- // passed as the top argument') node that the given node is
- // contained in. Return null if the given node is not inside the top
- // node.
- function topLevelNodeAt(node, top) {
- while (node && node.parentNode != top)
- node = node.parentNode;
- return node;
- }
-
- // Find the top-level node that contains the node before this one.
- function topLevelNodeBefore(node, top) {
- while (!node.previousSibling && node.parentNode != top)
- node = node.parentNode;
- return topLevelNodeAt(node.previousSibling, top);
- }
-
- var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
-
- select.scrollToNode = function(element) {
- if (!element) return;
- var doc = element.ownerDocument, body = doc.body,
- win = (doc.defaultView || doc.parentWindow),
- html = doc.documentElement,
- atEnd = !element.nextSibling || !element.nextSibling.nextSibling
- || !element.nextSibling.nextSibling.nextSibling;
- // In Opera (and recent Webkit versions), BR elements *always*
- // have a scrollTop property of zero.
- var compensateHack = 0;
- while (element && !element.offsetTop) {
- compensateHack++;
- element = element.previousSibling;
- }
- // atEnd is another kludge for these browsers -- if the cursor is
- // at the end of the document, and the node doesn't have an
- // offset, just scroll to the end.
- if (compensateHack == 0) atEnd = false;
-
- var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, pos = element;
- while (pos && pos.offsetParent) {
- y += pos.offsetTop;
- // Don't count X offset for nodes
- if (!isBR(pos))
- x += pos.offsetLeft;
- pos = pos.offsetParent;
- }
-
- var scroll_x = body.scrollLeft || html.scrollLeft || 0,
- scroll_y = body.scrollTop || html.scrollTop || 0,
- screen_x = x - scroll_x, screen_y = y - scroll_y, scroll = false;
-
- if (screen_x < 0 || screen_x > (win.innerWidth || html.clientWidth || 0)) {
- scroll_x = x;
- scroll = true;
- }
- if (screen_y < 0 || atEnd || screen_y > (win.innerHeight || html.clientHeight || 0) - 50) {
- scroll_y = atEnd ? 1e10 : y;
- scroll = true;
- }
- if (scroll) win.scrollTo(scroll_x, scroll_y);
- };
-
- select.scrollToCursor = function(container) {
- select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild);
- };
-
- // Used to prevent restoring a selection when we do not need to.
- var currentSelection = null;
-
- select.snapshotChanged = function() {
- if (currentSelection) currentSelection.changed = true;
- };
-
- // This is called by the code in editor.js whenever it is replacing
- // a text node. The function sees whether the given oldNode is part
- // of the current selection, and updates this selection if it is.
- // Because nodes are often only partially replaced, the length of
- // the part that gets replaced has to be taken into account -- the
- // selection might stay in the oldNode if the newNode is smaller
- // than the selection's offset. The offset argument is needed in
- // case the selection does move to the new object, and the given
- // length is not the whole length of the new node (part of it might
- // have been used to replace another node).
- select.snapshotReplaceNode = function(from, to, length, offset) {
- if (!currentSelection) return;
-
- function replace(point) {
- if (from == point.node) {
- currentSelection.changed = true;
- if (length && point.offset > length) {
- point.offset -= length;
- }
- else {
- point.node = to;
- point.offset += (offset || 0);
- }
- }
- }
- replace(currentSelection.start);
- replace(currentSelection.end);
- };
-
- select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
- if (!currentSelection) return;
-
- function move(point) {
- if (from == point.node && (!ifAtStart || point.offset == 0)) {
- currentSelection.changed = true;
- point.node = to;
- if (relative) point.offset = Math.max(0, point.offset + distance);
- else point.offset = distance;
- }
- }
- move(currentSelection.start);
- move(currentSelection.end);
- };
-
- // Most functions are defined in two ways, one for the IE selection
- // model, one for the W3C one.
- if (select.ie_selection) {
- function selectionNode(win, start) {
- var range = win.document.selection.createRange();
- range.collapse(start);
-
- function nodeAfter(node) {
- var found = null;
- while (!found && node) {
- found = node.nextSibling;
- node = node.parentNode;
- }
- return nodeAtStartOf(found);
- }
-
- function nodeAtStartOf(node) {
- while (node && node.firstChild) node = node.firstChild;
- return {node: node, offset: 0};
- }
-
- var containing = range.parentElement();
- if (!isAncestor(win.document.body, containing)) return null;
- if (!containing.firstChild) return nodeAtStartOf(containing);
-
- var working = range.duplicate();
- working.moveToElementText(containing);
- working.collapse(true);
- for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
- if (cur.nodeType == 3) {
- var size = cur.nodeValue.length;
- working.move("character", size);
- }
- else {
- working.moveToElementText(cur);
- working.collapse(false);
- }
-
- var dir = range.compareEndPoints("StartToStart", working);
- if (dir == 0) return nodeAfter(cur);
- if (dir == 1) continue;
- if (cur.nodeType != 3) return nodeAtStartOf(cur);
-
- working.setEndPoint("StartToEnd", range);
- return {node: cur, offset: size - working.text.length};
- }
- return nodeAfter(containing);
- }
-
- select.markSelection = function(win) {
- currentSelection = null;
- var sel = win.document.selection;
- if (!sel) return;
- var start = selectionNode(win, true),
- end = selectionNode(win, false);
- if (!start || !end) return;
- currentSelection = {start: start, end: end, window: win, changed: false};
- };
-
- select.selectMarked = function() {
- if (!currentSelection || !currentSelection.changed) return;
- var win = currentSelection.window, doc = win.document;
-
- function makeRange(point) {
- var range = doc.body.createTextRange(),
- node = point.node;
- if (!node) {
- range.moveToElementText(currentSelection.window.document.body);
- range.collapse(false);
- }
- else if (node.nodeType == 3) {
- range.moveToElementText(node.parentNode);
- var offset = point.offset;
- while (node.previousSibling) {
- node = node.previousSibling;
- offset += (node.innerText || "").length;
- }
- range.move("character", offset);
- }
- else {
- range.moveToElementText(node);
- range.collapse(true);
- }
- return range;
- }
-
- var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
- start.setEndPoint("StartToEnd", end);
- start.select();
- };
-
- // Get the top-level node that one end of the cursor is inside or
- // after. Note that this returns false for 'no cursor', and null
- // for 'start of document'.
- select.selectionTopNode = function(container, start) {
- var selection = container.ownerDocument.selection;
- if (!selection) return false;
-
- var range = selection.createRange(), range2 = range.duplicate();
- range.collapse(start);
- var around = range.parentElement();
- if (around && isAncestor(container, around)) {
- // Only use this node if the selection is not at its start.
- range2.moveToElementText(around);
- if (range.compareEndPoints("StartToStart", range2) == 1)
- return topLevelNodeAt(around, container);
- }
-
- // Move the start of a range to the start of a node,
- // compensating for the fact that you can't call
- // moveToElementText with text nodes.
- function moveToNodeStart(range, node) {
- if (node.nodeType == 3) {
- var count = 0, cur = node.previousSibling;
- while (cur && cur.nodeType == 3) {
- count += cur.nodeValue.length;
- cur = cur.previousSibling;
- }
- if (cur) {
- try{range.moveToElementText(cur);}
- catch(e){return false;}
- range.collapse(false);
- }
- else range.moveToElementText(node.parentNode);
- if (count) range.move("character", count);
- }
- else {
- try{range.moveToElementText(node);}
- catch(e){return false;}
- }
- return true;
- }
-
- // Do a binary search through the container object, comparing
- // the start of each node to the selection
- var start = 0, end = container.childNodes.length - 1;
- while (start < end) {
- var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
- if (!node) return false; // Don't ask. IE6 manages this sometimes.
- if (!moveToNodeStart(range2, node)) return false;
- if (range.compareEndPoints("StartToStart", range2) == 1)
- start = middle;
- else
- end = middle - 1;
- }
- return container.childNodes[start] || null;
- };
-
- // Place the cursor after this.start. This is only useful when
- // manually moving the cursor instead of restoring it to its old
- // position.
- select.focusAfterNode = function(node, container) {
- var range = container.ownerDocument.body.createTextRange();
- range.moveToElementText(node || container);
- range.collapse(!node);
- range.select();
- };
-
- select.somethingSelected = function(win) {
- var sel = win.document.selection;
- return sel && (sel.createRange().text != "");
- };
-
- function insertAtCursor(window, html) {
- var selection = window.document.selection;
- if (selection) {
- var range = selection.createRange();
- range.pasteHTML(html);
- range.collapse(false);
- range.select();
- }
- }
-
- // Used to normalize the effect of the enter key, since browsers
- // do widely different things when pressing enter in designMode.
- select.insertNewlineAtCursor = function(window) {
- insertAtCursor(window, " ");
- };
-
- select.insertTabAtCursor = function(window) {
- insertAtCursor(window, fourSpaces);
- };
-
- // Get the BR node at the start of the line on which the cursor
- // currently is, and the offset into the line. Returns null as
- // node if cursor is on first line.
- select.cursorPos = function(container, start) {
- var selection = container.ownerDocument.selection;
- if (!selection) return null;
-
- var topNode = select.selectionTopNode(container, start);
- while (topNode && !isBR(topNode))
- topNode = topNode.previousSibling;
-
- var range = selection.createRange(), range2 = range.duplicate();
- range.collapse(start);
- if (topNode) {
- range2.moveToElementText(topNode);
- range2.collapse(false);
- }
- else {
- // When nothing is selected, we can get all kinds of funky errors here.
- try { range2.moveToElementText(container); }
- catch (e) { return null; }
- range2.collapse(true);
- }
- range.setEndPoint("StartToStart", range2);
-
- return {node: topNode, offset: range.text.length};
- };
-
- select.setCursorPos = function(container, from, to) {
- function rangeAt(pos) {
- var range = container.ownerDocument.body.createTextRange();
- if (!pos.node) {
- range.moveToElementText(container);
- range.collapse(true);
- }
- else {
- range.moveToElementText(pos.node);
- range.collapse(false);
- }
- range.move("character", pos.offset);
- return range;
- }
-
- var range = rangeAt(from);
- if (to && to != from)
- range.setEndPoint("EndToEnd", rangeAt(to));
- range.select();
- }
-
- // Some hacks for storing and re-storing the selection when the editor loses and regains focus.
- select.selectionCoords = function (win) {
- var selection = win.document.selection;
- if (!selection) return null;
- var start = selection.createRange(), end = start.duplicate();
- start.collapse(true);
- end.collapse(false);
-
- var body = win.document.body;
- return {start: {x: start.boundingLeft + body.scrollLeft - 1,
- y: start.boundingTop + body.scrollTop},
- end: {x: end.boundingLeft + body.scrollLeft - 1,
- y: end.boundingTop + body.scrollTop}};
- };
-
- // Restore a stored selection.
- select.selectCoords = function(win, coords) {
- if (!coords) return;
-
- var range1 = win.document.body.createTextRange(), range2 = range1.duplicate();
- // This can fail for various hard-to-handle reasons.
- try {
- range1.moveToPoint(coords.start.x, coords.start.y);
- range2.moveToPoint(coords.end.x, coords.end.y);
- range1.setEndPoint("EndToStart", range2);
- range1.select();
- } catch(e) {}
- };
- }
- // W3C model
- else {
- // Store start and end nodes, and offsets within these, and refer
- // back to the selection object from those nodes, so that this
- // object can be updated when the nodes are replaced before the
- // selection is restored.
- select.markSelection = function (win) {
- var selection = win.getSelection();
- if (!selection || selection.rangeCount == 0)
- return (currentSelection = null);
- var range = selection.getRangeAt(0);
-
- currentSelection = {
- start: {node: range.startContainer, offset: range.startOffset},
- end: {node: range.endContainer, offset: range.endOffset},
- window: win,
- changed: false
- };
-
- // We want the nodes right at the cursor, not one of their
- // ancestors with a suitable offset. This goes down the DOM tree
- // until a 'leaf' is reached (or is it *up* the DOM tree?).
- function normalize(point){
- while (point.node.nodeType != 3 && !isBR(point.node)) {
- var newNode = point.node.childNodes[point.offset] || point.node.nextSibling;
- point.offset = 0;
- while (!newNode && point.node.parentNode) {
- point.node = point.node.parentNode;
- newNode = point.node.nextSibling;
- }
- point.node = newNode;
- if (!newNode)
- break;
- }
- }
-
- normalize(currentSelection.start);
- normalize(currentSelection.end);
- };
-
- select.selectMarked = function () {
- var cs = currentSelection;
- if (!(cs && (cs.changed || (webkit && cs.start.node == cs.end.node)))) return;
- var win = cs.window, range = win.document.createRange();
-
- function setPoint(point, which) {
- if (point.node) {
- // Some magic to generalize the setting of the start and end
- // of a range.
- if (point.offset == 0)
- range["set" + which + "Before"](point.node);
- else
- range["set" + which](point.node, point.offset);
- }
- else {
- range.setStartAfter(win.document.body.lastChild || win.document.body);
- }
- }
-
- setPoint(cs.end, "End");
- setPoint(cs.start, "Start");
- selectRange(range, win);
- };
-
- // Helper for selecting a range object.
- function selectRange(range, window) {
- var selection = window.getSelection();
- selection.removeAllRanges();
- selection.addRange(range);
- };
- function selectionRange(window) {
- var selection = window.getSelection();
- if (!selection || selection.rangeCount == 0)
- return false;
- else
- return selection.getRangeAt(0);
- }
-
- // Finding the top-level node at the cursor in the W3C is, as you
- // can see, quite an involved process.
- select.selectionTopNode = function(container, start) {
- var range = selectionRange(container.ownerDocument.defaultView);
- if (!range) return false;
-
- var node = start ? range.startContainer : range.endContainer;
- var offset = start ? range.startOffset : range.endOffset;
- // Work around (yet another) bug in Opera's selection model.
- if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
- container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
- offset--;
-
- // For text nodes, we look at the node itself if the cursor is
- // inside, or at the node before it if the cursor is at the
- // start.
- if (node.nodeType == 3){
- if (offset > 0)
- return topLevelNodeAt(node, container);
- else
- return topLevelNodeBefore(node, container);
- }
- // Occasionally, browsers will return the HTML node as
- // selection. If the offset is 0, we take the start of the frame
- // ('after null'), otherwise, we take the last node.
- else if (node.nodeName.toUpperCase() == "HTML") {
- return (offset == 1 ? null : container.lastChild);
- }
- // If the given node is our 'container', we just look up the
- // correct node by using the offset.
- else if (node == container) {
- return (offset == 0) ? null : node.childNodes[offset - 1];
- }
- // In any other case, we have a regular node. If the cursor is
- // at the end of the node, we use the node itself, if it is at
- // the start, we use the node before it, and in any other
- // case, we look up the child before the cursor and use that.
- else {
- if (offset == node.childNodes.length)
- return topLevelNodeAt(node, container);
- else if (offset == 0)
- return topLevelNodeBefore(node, container);
- else
- return topLevelNodeAt(node.childNodes[offset - 1], container);
- }
- };
-
- select.focusAfterNode = function(node, container) {
- var win = container.ownerDocument.defaultView,
- range = win.document.createRange();
- range.setStartBefore(container.firstChild || container);
- // In Opera, setting the end of a range at the end of a line
- // (before a BR) will cause the cursor to appear on the next
- // line, so we set the end inside of the start node when
- // possible.
- if (node && !node.firstChild)
- range.setEndAfter(node);
- else if (node)
- range.setEnd(node, node.childNodes.length);
- else
- range.setEndBefore(container.firstChild || container);
- range.collapse(false);
- selectRange(range, win);
- };
-
- select.somethingSelected = function(win) {
- var range = selectionRange(win);
- return range && !range.collapsed;
- };
-
- function insertNodeAtCursor(window, node) {
- var range = selectionRange(window);
- if (!range) return;
-
- range.deleteContents();
- range.insertNode(node);
- webkitLastLineHack(window.document.body);
- range = window.document.createRange();
- range.selectNode(node);
- range.collapse(false);
- selectRange(range, window);
- }
-
- select.insertNewlineAtCursor = function(window) {
- insertNodeAtCursor(window, window.document.createElement("BR"));
- };
-
- select.insertTabAtCursor = function(window) {
- insertNodeAtCursor(window, window.document.createTextNode(fourSpaces));
- };
-
- select.cursorPos = function(container, start) {
- var range = selectionRange(window);
- if (!range) return;
-
- var topNode = select.selectionTopNode(container, start);
- while (topNode && !isBR(topNode))
- topNode = topNode.previousSibling;
-
- range = range.cloneRange();
- range.collapse(start);
- if (topNode)
- range.setStartAfter(topNode);
- else
- range.setStartBefore(container);
- return {node: topNode, offset: range.toString().length};
- };
-
- select.setCursorPos = function(container, from, to) {
- var win = container.ownerDocument.defaultView,
- range = win.document.createRange();
-
- function setPoint(node, offset, side) {
- if (!node)
- node = container.firstChild;
- else
- node = node.nextSibling;
-
- if (!node)
- return;
-
- if (offset == 0) {
- range["set" + side + "Before"](node);
- return true;
- }
-
- var backlog = []
- function decompose(node) {
- if (node.nodeType == 3)
- backlog.push(node);
- else
- forEach(node.childNodes, decompose);
- }
- while (true) {
- while (node && !backlog.length) {
- decompose(node);
- node = node.nextSibling;
- }
- var cur = backlog.shift();
- if (!cur) return false;
-
- var length = cur.nodeValue.length;
- if (length >= offset) {
- range["set" + side](cur, offset);
- return true;
- }
- offset -= length;
- }
- }
-
- to = to || from;
- if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
- selectRange(range, win);
- };
- }
-})();
-
-;;;;;
-
-/**
- * Storage and control for undo information within a CodeMirror
- * editor. 'Why on earth is such a complicated mess required for
- * that?', I hear you ask. The goal, in implementing this, was to make
- * the complexity of storing and reverting undo information depend
- * only on the size of the edited or restored content, not on the size
- * of the whole document. This makes it necessary to use a kind of
- * 'diff' system, which, when applied to a DOM tree, causes some
- * complexity and hackery.
- *
- * In short, the editor 'touches' BR elements as it parses them, and
- * the History stores these. When nothing is touched in commitDelay
- * milliseconds, the changes are committed: It goes over all touched
- * nodes, throws out the ones that did not change since last commit or
- * are no longer in the document, and assembles the rest into zero or
- * more 'chains' -- arrays of adjacent lines. Links back to these
- * chains are added to the BR nodes, while the chain that previously
- * spanned these nodes is added to the undo history. Undoing a change
- * means taking such a chain off the undo history, restoring its
- * content (text is saved per line) and linking it back into the
- * document.
- */
-
-// A history object needs to know about the DOM container holding the
-// document, the maximum amount of undo levels it should store, the
-// delay (of no input) after which it commits a set of changes, and,
-// unfortunately, the 'parent' window -- a window that is not in
-// designMode, and on which setTimeout works in every browser.
-function History(container, maxDepth, commitDelay, editor, onChange) {
- this.container = container;
- this.maxDepth = maxDepth; this.commitDelay = commitDelay;
- this.editor = editor; this.parent = editor.parent;
- this.onChange = onChange;
- // This line object represents the initial, empty editor.
- var initial = {text: "", from: null, to: null};
- // As the borders between lines are represented by BR elements, the
- // start of the first line and the end of the last one are
- // represented by null. Since you can not store any properties
- // (links to line objects) in null, these properties are used in
- // those cases.
- this.first = initial; this.last = initial;
- // Similarly, a 'historyTouched' property is added to the BR in
- // front of lines that have already been touched, and 'firstTouched'
- // is used for the first line.
- this.firstTouched = false;
- // History is the set of committed changes, touched is the set of
- // nodes touched since the last commit.
- this.history = []; this.redoHistory = []; this.touched = [];
-}
-
-History.prototype = {
- // Schedule a commit (if no other touches come in for commitDelay
- // milliseconds).
- scheduleCommit: function() {
- var self = this;
- this.parent.clearTimeout(this.commitTimeout);
- this.commitTimeout = this.parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
- },
-
- // Mark a node as touched. Null is a valid argument.
- touch: function(node) {
- this.setTouched(node);
- this.scheduleCommit();
- },
-
- // Undo the last change.
- undo: function() {
- // Make sure pending changes have been committed.
- this.commit();
-
- if (this.history.length) {
- // Take the top diff from the history, apply it, and store its
- // shadow in the redo history.
- var item = this.history.pop();
- this.redoHistory.push(this.updateTo(item, "applyChain"));
- if (this.onChange) this.onChange();
- return this.chainNode(item);
- }
- },
-
- // Redo the last undone change.
- redo: function() {
- this.commit();
- if (this.redoHistory.length) {
- // The inverse of undo, basically.
- var item = this.redoHistory.pop();
- this.addUndoLevel(this.updateTo(item, "applyChain"));
- if (this.onChange) this.onChange();
- return this.chainNode(item);
- }
- },
-
- clear: function() {
- this.history = [];
- this.redoHistory = [];
- },
-
- // Ask for the size of the un/redo histories.
- historySize: function() {
- return {undo: this.history.length, redo: this.redoHistory.length};
- },
-
- // Push a changeset into the document.
- push: function(from, to, lines) {
- var chain = [];
- for (var i = 0; i < lines.length; i++) {
- var end = (i == lines.length - 1) ? to : this.container.ownerDocument.createElement("BR");
- chain.push({from: from, to: end, text: cleanText(lines[i])});
- from = end;
- }
- this.pushChains([chain], from == null && to == null);
- },
-
- pushChains: function(chains, doNotHighlight) {
- this.commit(doNotHighlight);
- this.addUndoLevel(this.updateTo(chains, "applyChain"));
- this.redoHistory = [];
- },
-
- // Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
- chainNode: function(chains) {
- for (var i = 0; i < chains.length; i++) {
- var start = chains[i][0], node = start && (start.from || start.to);
- if (node) return node;
- }
- },
-
- // Clear the undo history, make the current document the start
- // position.
- reset: function() {
- this.history = []; this.redoHistory = [];
- },
-
- textAfter: function(br) {
- return this.after(br).text;
- },
-
- nodeAfter: function(br) {
- return this.after(br).to;
- },
-
- nodeBefore: function(br) {
- return this.before(br).from;
- },
-
- // Commit unless there are pending dirty nodes.
- tryCommit: function() {
- if (!window.History) return; // Stop when frame has been unloaded
- if (this.editor.highlightDirty()) this.commit(true);
- else this.scheduleCommit();
- },
-
- // Check whether the touched nodes hold any changes, if so, commit
- // them.
- commit: function(doNotHighlight) {
- this.parent.clearTimeout(this.commitTimeout);
- // Make sure there are no pending dirty nodes.
- if (!doNotHighlight) this.editor.highlightDirty(true);
- // Build set of chains.
- var chains = this.touchedChains(), self = this;
-
- if (chains.length) {
- this.addUndoLevel(this.updateTo(chains, "linkChain"));
- this.redoHistory = [];
- if (this.onChange) this.onChange();
- }
- },
-
- // [ end of public interface ]
-
- // Update the document with a given set of chains, return its
- // shadow. updateFunc should be "applyChain" or "linkChain". In the
- // second case, the chains are taken to correspond the the current
- // document, and only the state of the line data is updated. In the
- // first case, the content of the chains is also pushed iinto the
- // document.
- updateTo: function(chains, updateFunc) {
- var shadows = [], dirty = [];
- for (var i = 0; i < chains.length; i++) {
- shadows.push(this.shadowChain(chains[i]));
- dirty.push(this[updateFunc](chains[i]));
- }
- if (updateFunc == "applyChain")
- this.notifyDirty(dirty);
- return shadows;
- },
-
- // Notify the editor that some nodes have changed.
- notifyDirty: function(nodes) {
- forEach(nodes, method(this.editor, "addDirtyNode"))
- this.editor.scheduleHighlight();
- },
-
- // Link a chain into the DOM nodes (or the first/last links for null
- // nodes).
- linkChain: function(chain) {
- for (var i = 0; i < chain.length; i++) {
- var line = chain[i];
- if (line.from) line.from.historyAfter = line;
- else this.first = line;
- if (line.to) line.to.historyBefore = line;
- else this.last = line;
- }
- },
-
- // Get the line object after/before a given node.
- after: function(node) {
- return node ? node.historyAfter : this.first;
- },
- before: function(node) {
- return node ? node.historyBefore : this.last;
- },
-
- // Mark a node as touched if it has not already been marked.
- setTouched: function(node) {
- if (node) {
- if (!node.historyTouched) {
- this.touched.push(node);
- node.historyTouched = true;
- }
- }
- else {
- this.firstTouched = true;
- }
- },
-
- // Store a new set of undo info, throw away info if there is more of
- // it than allowed.
- addUndoLevel: function(diffs) {
- this.history.push(diffs);
- if (this.history.length > this.maxDepth)
- this.history.shift();
- },
-
- // Build chains from a set of touched nodes.
- touchedChains: function() {
- var self = this;
-
- // The temp system is a crummy hack to speed up determining
- // whether a (currently touched) node has a line object associated
- // with it. nullTemp is used to store the object for the first
- // line, other nodes get it stored in their historyTemp property.
- var nullTemp = null;
- function temp(node) {return node ? node.historyTemp : nullTemp;}
- function setTemp(node, line) {
- if (node) node.historyTemp = line;
- else nullTemp = line;
- }
-
- function buildLine(node) {
- var text = [];
- for (var cur = node ? node.nextSibling : self.container.firstChild;
- cur && !isBR(cur); cur = cur.nextSibling)
- if (cur.currentText) text.push(cur.currentText);
- return {from: node, to: cur, text: cleanText(text.join(""))};
- }
-
- // Filter out unchanged lines and nodes that are no longer in the
- // document. Build up line objects for remaining nodes.
- var lines = [];
- if (self.firstTouched) self.touched.push(null);
- forEach(self.touched, function(node) {
- if (node && node.parentNode != self.container) return;
-
- if (node) node.historyTouched = false;
- else self.firstTouched = false;
-
- var line = buildLine(node), shadow = self.after(node);
- if (!shadow || shadow.text != line.text || shadow.to != line.to) {
- lines.push(line);
- setTemp(node, line);
- }
- });
-
- // Get the BR element after/before the given node.
- function nextBR(node, dir) {
- var link = dir + "Sibling", search = node[link];
- while (search && !isBR(search))
- search = search[link];
- return search;
- }
-
- // Assemble line objects into chains by scanning the DOM tree
- // around them.
- var chains = []; self.touched = [];
- forEach(lines, function(line) {
- // Note that this makes the loop skip line objects that have
- // been pulled into chains by lines before them.
- if (!temp(line.from)) return;
-
- var chain = [], curNode = line.from, safe = true;
- // Put any line objects (referred to by temp info) before this
- // one on the front of the array.
- while (true) {
- var curLine = temp(curNode);
- if (!curLine) {
- if (safe) break;
- else curLine = buildLine(curNode);
- }
- chain.unshift(curLine);
- setTemp(curNode, null);
- if (!curNode) break;
- safe = self.after(curNode);
- curNode = nextBR(curNode, "previous");
- }
- curNode = line.to; safe = self.before(line.from);
- // Add lines after this one at end of array.
- while (true) {
- if (!curNode) break;
- var curLine = temp(curNode);
- if (!curLine) {
- if (safe) break;
- else curLine = buildLine(curNode);
- }
- chain.push(curLine);
- setTemp(curNode, null);
- safe = self.before(curNode);
- curNode = nextBR(curNode, "next");
- }
- chains.push(chain);
- });
-
- return chains;
- },
-
- // Find the 'shadow' of a given chain by following the links in the
- // DOM nodes at its start and end.
- shadowChain: function(chain) {
- var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
- while (true) {
- shadows.push(next);
- var nextNode = next.to;
- if (!nextNode || nextNode == end)
- break;
- else
- next = nextNode.historyAfter || this.before(end);
- // (The this.before(end) is a hack -- FF sometimes removes
- // properties from BR nodes, in which case the best we can hope
- // for is to not break.)
- }
- return shadows;
- },
-
- // Update the DOM tree to contain the lines specified in a given
- // chain, link this chain into the DOM nodes.
- applyChain: function(chain) {
- // Some attempt is made to prevent the cursor from jumping
- // randomly when an undo or redo happens. It still behaves a bit
- // strange sometimes.
- var cursor = select.cursorPos(this.container, false), self = this;
-
- // Remove all nodes in the DOM tree between from and to (null for
- // start/end of container).
- function removeRange(from, to) {
- var pos = from ? from.nextSibling : self.container.firstChild;
- while (pos != to) {
- var temp = pos.nextSibling;
- removeElement(pos);
- pos = temp;
- }
- }
-
- var start = chain[0].from, end = chain[chain.length - 1].to;
- // Clear the space where this change has to be made.
- removeRange(start, end);
-
- // Insert the content specified by the chain into the DOM tree.
- for (var i = 0; i < chain.length; i++) {
- var line = chain[i];
- // The start and end of the space are already correct, but BR
- // tags inside it have to be put back.
- if (i > 0)
- self.container.insertBefore(line.from, end);
-
- // Add the text.
- var node = makePartSpan(fixSpaces(line.text), this.container.ownerDocument);
- self.container.insertBefore(node, end);
- // See if the cursor was on this line. Put it back, adjusting
- // for changed line length, if it was.
- if (cursor && cursor.node == line.from) {
- var cursordiff = 0;
- var prev = this.after(line.from);
- if (prev && i == chain.length - 1) {
- // Only adjust if the cursor is after the unchanged part of
- // the line.
- for (var match = 0; match < cursor.offset &&
- line.text.charAt(match) == prev.text.charAt(match); match++);
- if (cursor.offset > match)
- cursordiff = line.text.length - prev.text.length;
- }
- select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
- }
- // Cursor was in removed line, this is last new line.
- else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
- select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
- }
- }
-
- // Anchor the chain in the DOM tree.
- this.linkChain(chain);
- return start;
- }
-};
-
-;;;;;
-
-/* The Editor object manages the content of the editable frame. It
- * catches events, colours nodes, and indents lines. This file also
- * holds some functions for transforming arbitrary DOM structures into
- * plain sequences of and elements
- */
-
-// Make sure a string does not contain two consecutive 'collapseable'
-// whitespace characters.
-function makeWhiteSpace(n) {
- var buffer = [], nb = true;
- for (; n > 0; n--) {
- buffer.push((nb || n == 1) ? nbsp : " ");
- nb = !nb;
- }
- return buffer.join("");
-}
-
-// Create a set of white-space characters that will not be collapsed
-// by the browser, but will not break text-wrapping either.
-function fixSpaces(string) {
- if (string.charAt(0) == " ") string = nbsp + string.slice(1);
- return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);})
- .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
-}
-
-function cleanText(text) {
- return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
-}
-
-// Create a SPAN node with the expected properties for document part
-// spans.
-function makePartSpan(value, doc) {
- var text = value;
- if (value.nodeType == 3) text = value.nodeValue;
- else value = doc.createTextNode(text);
-
- var span = doc.createElement("SPAN");
- span.isPart = true;
- span.appendChild(value);
- span.currentText = text;
- return span;
-}
-
-// On webkit, when the last BR of the document does not have text
-// behind it, the cursor can not be put on the line after it. This
-// makes pressing enter at the end of the document occasionally do
-// nothing (or at least seem to do nothing). To work around it, this
-// function makes sure the document ends with a span containing a
-// zero-width space character. The traverseDOM iterator filters such
-// character out again, so that the parsers won't see them. This
-// function is called from a few strategic places to make sure the
-// zwsp is restored after the highlighting process eats it.
-var webkitLastLineHack = webkit ?
- function(container) {
- var last = container.lastChild;
- if (!last || !last.isPart || last.textContent != "\u200b")
- container.appendChild(makePartSpan("\u200b", container.ownerDocument));
- } : function() {};
-
-var Editor = (function(){
- // The HTML elements whose content should be suffixed by a newline
- // when converting them to flat text.
- var newlineElements = {"P": true, "DIV": true, "LI": true};
-
- function asEditorLines(string) {
- var tab = makeWhiteSpace(indentUnit);
- return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
- }
-
- // Helper function for traverseDOM. Flattens an arbitrary DOM node
- // into an array of textnodes and tags.
- function simplifyDOM(root, atEnd) {
- var doc = root.ownerDocument;
- var result = [];
- var leaving = true;
-
- function simplifyNode(node, top) {
- if (node.nodeType == 3) {
- var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
- if (text.length) leaving = false;
- result.push(node);
- }
- else if (isBR(node) && node.childNodes.length == 0) {
- leaving = true;
- result.push(node);
- }
- else {
- forEach(node.childNodes, simplifyNode);
- if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
- leaving = true;
- if (!atEnd || !top)
- result.push(doc.createElement("BR"));
- }
- }
- }
-
- simplifyNode(root, true);
- return result;
- }
-
- // Creates a MochiKit-style iterator that goes over a series of DOM
- // nodes. The values it yields are strings, the textual content of
- // the nodes. It makes sure that all nodes up to and including the
- // one whose text is being yielded have been 'normalized' to be just
- // and elements.
- // See the story.html file for some short remarks about the use of
- // continuation-passing style in this iterator.
- function traverseDOM(start){
- function yield(value, c){cc = c; return value;}
- function push(fun, arg, c){return function(){return fun(arg, c);};}
- function stop(){cc = stop; throw StopIteration;};
- var cc = push(scanNode, start, stop);
- var owner = start.ownerDocument;
- var nodeQueue = [];
-
- // Create a function that can be used to insert nodes after the
- // one given as argument.
- function pointAt(node){
- var parent = node.parentNode;
- var next = node.nextSibling;
- return function(newnode) {
- parent.insertBefore(newnode, next);
- };
- }
- var point = null;
-
- // Insert a normalized node at the current point. If it is a text
- // node, wrap it in a , and give that span a currentText
- // property -- this is used to cache the nodeValue, because
- // directly accessing nodeValue is horribly slow on some browsers.
- // The dirty property is used by the highlighter to determine
- // which parts of the document have to be re-highlighted.
- function insertPart(part){
- var text = "\n";
- if (part.nodeType == 3) {
- select.snapshotChanged();
- part = makePartSpan(part, owner);
- text = part.currentText;
- }
- part.dirty = true;
- nodeQueue.push(part);
- point(part);
- return text;
- }
-
- // Extract the text and newlines from a DOM node, insert them into
- // the document, and yield the textual content. Used to replace
- // non-normalized nodes.
- function writeNode(node, c, end) {
- var toYield = [];
- forEach(simplifyDOM(node, end), function(part) {
- toYield.push(insertPart(part));
- });
- return yield(toYield.join(""), c);
- }
-
- // Check whether a node is a normalized element.
- function partNode(node){
- if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
- node.currentText = node.firstChild.nodeValue;
- return !/[\n\t\r]/.test(node.currentText);
- }
- return false;
- }
-
- // Handle a node. Add its successor to the continuation if there
- // is one, find out whether the node is normalized. If it is,
- // yield its content, otherwise, normalize it (writeNode will take
- // care of yielding).
- function scanNode(node, c){
- if (node.nextSibling)
- c = push(scanNode, node.nextSibling, c);
-
- if (partNode(node)){
- nodeQueue.push(node);
- return yield(node.currentText, c);
- }
- else if (isBR(node)) {
- nodeQueue.push(node);
- return yield("\n", c);
- }
- else {
- var end = !node.nextSibling;
- point = pointAt(node);
- removeElement(node);
- return writeNode(node, c, end);
- }
- }
-
- // MochiKit iterators are objects with a next function that
- // returns the next value or throws StopIteration when there are
- // no more values.
- return {next: function(){return cc();}, nodes: nodeQueue};
- }
-
- // Determine the text size of a processed node.
- function nodeSize(node) {
- return isBR(node) ? 1 : node.currentText.length;
- }
-
- // Search backwards through the top-level nodes until the next BR or
- // the start of the frame.
- function startOfLine(node) {
- while (node && !isBR(node)) node = node.previousSibling;
- return node;
- }
- function endOfLine(node, container) {
- if (!node) node = container.firstChild;
- else if (isBR(node)) node = node.nextSibling;
-
- while (node && !isBR(node)) node = node.nextSibling;
- return node;
- }
-
- function time() {return new Date().getTime();}
-
- // Client interface for searching the content of the editor. Create
- // these by calling CodeMirror.getSearchCursor. To use, call
- // findNext on the resulting object -- this returns a boolean
- // indicating whether anything was found, and can be called again to
- // skip to the next find. Use the select and replace methods to
- // actually do something with the found locations.
- function SearchCursor(editor, string, fromCursor) {
- this.editor = editor;
- this.history = editor.history;
- this.history.commit();
-
- // Are we currently at an occurrence of the search string?
- this.atOccurrence = false;
- // The object stores a set of nodes coming after its current
- // position, so that when the current point is taken out of the
- // DOM tree, we can still try to continue.
- this.fallbackSize = 15;
- var cursor;
- // Start from the cursor when specified and a cursor can be found.
- if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
- this.line = cursor.node;
- this.offset = cursor.offset;
- }
- else {
- this.line = null;
- this.offset = 0;
- }
- this.valid = !!string;
-
- // Create a matcher function based on the kind of string we have.
- var target = string.split("\n"), self = this;
- this.matches = (target.length == 1) ?
- // For one-line strings, searching can be done simply by calling
- // indexOf on the current line.
- function() {
- var match = cleanText(self.history.textAfter(self.line).slice(self.offset)).indexOf(string);
- if (match > -1)
- return {from: {node: self.line, offset: self.offset + match},
- to: {node: self.line, offset: self.offset + match + string.length}};
- } :
- // Multi-line strings require internal iteration over lines, and
- // some clunky checks to make sure the first match ends at the
- // end of the line and the last match starts at the start.
- function() {
- var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
- var match = firstLine.lastIndexOf(target[0]);
- if (match == -1 || match != firstLine.length - target[0].length)
- return false;
- var startOffset = self.offset + match;
-
- var line = self.history.nodeAfter(self.line);
- for (var i = 1; i < target.length - 1; i++) {
- if (cleanText(self.history.textAfter(line)) != target[i])
- return false;
- line = self.history.nodeAfter(line);
- }
-
- if (cleanText(self.history.textAfter(line)).indexOf(target[target.length - 1]) != 0)
- return false;
-
- return {from: {node: self.line, offset: startOffset},
- to: {node: line, offset: target[target.length - 1].length}};
- };
- }
-
- SearchCursor.prototype = {
- findNext: function() {
- if (!this.valid) return false;
- this.atOccurrence = false;
- var self = this;
-
- // Go back to the start of the document if the current line is
- // no longer in the DOM tree.
- if (this.line && !this.line.parentNode) {
- this.line = null;
- this.offset = 0;
- }
-
- // Set the cursor's position one character after the given
- // position.
- function saveAfter(pos) {
- if (self.history.textAfter(pos.node).length > pos.offset) {
- self.line = pos.node;
- self.offset = pos.offset + 1;
- }
- else {
- self.line = self.history.nodeAfter(pos.node);
- self.offset = 0;
- }
- }
-
- while (true) {
- var match = this.matches();
- // Found the search string.
- if (match) {
- this.atOccurrence = match;
- saveAfter(match.from);
- return true;
- }
- this.line = this.history.nodeAfter(this.line);
- this.offset = 0;
- // End of document.
- if (!this.line) {
- this.valid = false;
- return false;
- }
- }
- },
-
- select: function() {
- if (this.atOccurrence) {
- select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
- select.scrollToCursor(this.editor.container);
- }
- },
-
- replace: function(string) {
- if (this.atOccurrence) {
- var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
- this.line = end.node;
- this.offset = end.offset;
- this.atOccurrence = false;
- }
- }
- };
-
- // The Editor object is the main inside-the-iframe interface.
- function Editor(options) {
- this.options = options;
- window.indentUnit = options.indentUnit;
- this.parent = parent;
- this.doc = document;
- var container = this.container = this.doc.body;
- this.win = window;
- this.history = new History(container, options.undoDepth, options.undoDelay,
- this, options.onChange);
- var self = this;
-
- if (!Editor.Parser)
- throw "No parser loaded.";
- if (options.parserConfig && Editor.Parser.configure)
- Editor.Parser.configure(options.parserConfig);
-
- if (!options.readOnly)
- select.setCursorPos(container, {node: null, offset: 0});
-
- this.dirty = [];
- if (options.content)
- this.importCode(options.content);
-
- if (!options.readOnly) {
- if (options.continuousScanning !== false) {
- this.scanner = this.documentScanner(options.passTime);
- this.delayScanning();
- }
-
- function setEditable() {
- // In IE, designMode frames can not run any scripts, so we use
- // contentEditable instead.
- if (document.body.contentEditable != undefined && internetExplorer)
- document.body.contentEditable = "true";
- else
- document.designMode = "on";
-
- document.documentElement.style.borderWidth = "0";
- if (!options.textWrapping)
- container.style.whiteSpace = "nowrap";
- }
-
- // If setting the frame editable fails, try again when the user
- // focus it (happens when the frame is not visible on
- // initialisation, in Firefox).
- try {
- setEditable();
- }
- catch(e) {
- var focusEvent = addEventHandler(document, "focus", function() {
- focusEvent();
- setEditable();
- }, true);
- }
-
- addEventHandler(document, "keydown", method(this, "keyDown"));
- addEventHandler(document, "keypress", method(this, "keyPress"));
- addEventHandler(document, "keyup", method(this, "keyUp"));
-
- function cursorActivity() {self.cursorActivity(false);}
- addEventHandler(document.body, "mouseup", cursorActivity);
- addEventHandler(document.body, "cut", cursorActivity);
-
- addEventHandler(document.body, "paste", function(event) {
- cursorActivity();
- var text = null;
- try {
- var clipboardData = event.clipboardData || window.clipboardData;
- if (clipboardData) text = clipboardData.getData('Text');
- }
- catch(e) {}
- if (text !== null) {
- self.replaceSelection(text);
- event.stop();
- }
- });
-
- addEventHandler(document.body, "beforepaste", method(this, "reroutePasteEvent"));
-
- if (this.options.autoMatchParens)
- addEventHandler(document.body, "click", method(this, "scheduleParenBlink"));
- }
- else if (!options.textWrapping) {
- container.style.whiteSpace = "nowrap";
- }
- }
-
- function isSafeKey(code) {
- return (code >= 16 && code <= 18) || // shift, control, alt
- (code >= 33 && code <= 40); // arrows, home, end
- }
-
- Editor.prototype = {
- // Import a piece of code into the editor.
- importCode: function(code) {
- this.history.push(null, null, asEditorLines(code));
- this.history.reset();
- },
-
- // Extract the code from the editor.
- getCode: function() {
- if (!this.container.firstChild)
- return "";
-
- var accum = [];
- select.markSelection(this.win);
- forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
- webkitLastLineHack(this.container);
- select.selectMarked();
- return cleanText(accum.join(""));
- },
-
- checkLine: function(node) {
- if (node === false || !(node == null || node.parentNode == this.container))
- throw parent.CodeMirror.InvalidLineHandle;
- },
-
- cursorPosition: function(start) {
- if (start == null) start = true;
- var pos = select.cursorPos(this.container, start);
- if (pos) return {line: pos.node, character: pos.offset};
- else return {line: null, character: 0};
- },
-
- firstLine: function() {
- return null;
- },
-
- lastLine: function() {
- if (this.container.lastChild) return startOfLine(this.container.lastChild);
- else return null;
- },
-
- nextLine: function(line) {
- this.checkLine(line);
- var end = endOfLine(line, this.container);
- return end || false;
- },
-
- prevLine: function(line) {
- this.checkLine(line);
- if (line == null) return false;
- return startOfLine(line.previousSibling);
- },
-
- selectLines: function(startLine, startOffset, endLine, endOffset) {
- this.checkLine(startLine);
- var start = {node: startLine, offset: startOffset}, end = null;
- if (endOffset !== undefined) {
- this.checkLine(endLine);
- end = {node: endLine, offset: endOffset};
- }
- select.setCursorPos(this.container, start, end);
- select.scrollToCursor(this.container);
- },
-
- lineContent: function(line) {
- this.checkLine(line);
- var accum = [];
- for (line = line ? line.nextSibling : this.container.firstChild;
- line && !isBR(line); line = line.nextSibling)
- accum.push(nodeText(line));
- return cleanText(accum.join(""));
- },
-
- setLineContent: function(line, content) {
- this.history.commit();
- this.replaceRange({node: line, offset: 0},
- {node: line, offset: this.history.textAfter(line).length},
- content);
- this.addDirtyNode(line);
- this.scheduleHighlight();
- },
-
- insertIntoLine: function(line, position, content) {
- var before = null;
- if (position == "end") {
- before = endOfLine(line, this.container);
- }
- else {
- for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
- if (position == 0) {
- before = cur;
- break;
- }
- var text = nodeText(cur);
- if (text.length > position) {
- before = cur.nextSibling;
- content = text.slice(0, position) + content + text.slice(position);
- removeElement(cur);
- break;
- }
- position -= text.length;
- }
- }
-
- var lines = asEditorLines(content), doc = this.container.ownerDocument;
- for (var i = 0; i < lines.length; i++) {
- if (i > 0) this.container.insertBefore(doc.createElement("BR"), before);
- this.container.insertBefore(makePartSpan(lines[i], doc), before);
- }
- this.addDirtyNode(line);
- this.scheduleHighlight();
- },
-
- // Retrieve the selected text.
- selectedText: function() {
- var h = this.history;
- h.commit();
-
- var start = select.cursorPos(this.container, true),
- end = select.cursorPos(this.container, false);
- if (!start || !end) return "";
-
- if (start.node == end.node)
- return h.textAfter(start.node).slice(start.offset, end.offset);
-
- var text = [h.textAfter(start.node).slice(start.offset)];
- for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
- text.push(h.textAfter(pos));
- text.push(h.textAfter(end.node).slice(0, end.offset));
- return cleanText(text.join("\n"));
- },
-
- // Replace the selection with another piece of text.
- replaceSelection: function(text) {
- this.history.commit();
-
- var start = select.cursorPos(this.container, true),
- end = select.cursorPos(this.container, false);
- if (!start || !end) return;
-
- end = this.replaceRange(start, end, text);
- select.setCursorPos(this.container, end);
- webkitLastLineHack(this.container);
- },
-
- reroutePasteEvent: function() {
- if (this.capturingPaste || window.opera) return;
- this.capturingPaste = true;
- var te = parent.document.createElement("TEXTAREA");
- te.style.position = "absolute";
- te.style.left = "-500px";
- te.style.width = "10px";
- te.style.top = nodeTop(frameElement) + "px";
- parent.document.body.appendChild(te);
- parent.focus();
- te.focus();
-
- var self = this;
- this.parent.setTimeout(function() {
- self.capturingPaste = false;
- self.win.focus();
- if (self.selectionSnapshot) // IE hack
- self.win.select.selectCoords(self.win, self.selectionSnapshot);
- var text = te.value;
- if (text) self.replaceSelection(text);
- removeElement(te);
- }, 10);
- },
-
- replaceRange: function(from, to, text) {
- var lines = asEditorLines(text);
- lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
- var lastLine = lines[lines.length - 1];
- lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
- var end = this.history.nodeAfter(to.node);
- this.history.push(from.node, end, lines);
- return {node: this.history.nodeBefore(end),
- offset: lastLine.length};
- },
-
- getSearchCursor: function(string, fromCursor) {
- return new SearchCursor(this, string, fromCursor);
- },
-
- // Re-indent the whole buffer
- reindent: function() {
- if (this.container.firstChild)
- this.indentRegion(null, this.container.lastChild);
- },
-
- reindentSelection: function(direction) {
- if (!select.somethingSelected(this.win)) {
- this.indentAtCursor(direction);
- }
- else {
- var start = select.selectionTopNode(this.container, true),
- end = select.selectionTopNode(this.container, false);
- if (start === false || end === false) return;
- this.indentRegion(start, end, direction);
- }
- },
-
- grabKeys: function(eventHandler, filter) {
- this.frozen = eventHandler;
- this.keyFilter = filter;
- },
- ungrabKeys: function() {
- this.frozen = "leave";
- this.keyFilter = null;
- },
-
- setParser: function(name) {
- Editor.Parser = window[name];
- if (this.container.firstChild) {
- forEach(this.container.childNodes, function(n) {
- if (n.nodeType != 3) n.dirty = true;
- });
- this.addDirtyNode(this.firstChild);
- this.scheduleHighlight();
- }
- },
-
- // Intercept enter and tab, and assign their new functions.
- keyDown: function(event) {
- if (this.frozen == "leave") this.frozen = null;
- if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) {
- event.stop();
- this.frozen(event);
- return;
- }
-
- var code = event.keyCode;
- // Don't scan when the user is typing.
- this.delayScanning();
- // Schedule a paren-highlight event, if configured.
- if (this.options.autoMatchParens)
- this.scheduleParenBlink();
-
- // The various checks for !altKey are there because AltGr sets both
- // ctrlKey and altKey to true, and should not be recognised as
- // Control.
- if (code == 13) { // enter
- if (event.ctrlKey && !event.altKey) {
- this.reparseBuffer();
- }
- else {
- select.insertNewlineAtCursor(this.win);
- this.indentAtCursor();
- select.scrollToCursor(this.container);
- }
- event.stop();
- }
- else if (code == 9 && this.options.tabMode != "default") { // tab
- this.handleTab(!event.ctrlKey && !event.shiftKey);
- event.stop();
- }
- else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
- this.handleTab(true);
- event.stop();
- }
- else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
- if (this.home())
- event.stop();
- }
- else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
- this.blinkParens(event.shiftKey);
- event.stop();
- }
- else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
- var cursor = select.selectionTopNode(this.container);
- if (cursor === false || !this.container.firstChild) return;
-
- if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
- else {
- var end = endOfLine(cursor, this.container);
- select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
- }
- event.stop();
- }
- else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
- if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
- select.scrollToNode(this.history.redo());
- event.stop();
- }
- else if (code == 90 || (safari && code == 8)) { // Z, backspace
- select.scrollToNode(this.history.undo());
- event.stop();
- }
- else if (code == 83 && this.options.saveFunction) { // S
- this.options.saveFunction();
- event.stop();
- }
- }
- },
-
- // Check for characters that should re-indent the current line,
- // and prevent Opera from handling enter and tab anyway.
- keyPress: function(event) {
- var electric = Editor.Parser.electricChars, self = this;
- // Hack for Opera, and Firefox on OS X, in which stopping a
- // keydown event does not prevent the associated keypress event
- // from happening, so we have to cancel enter and tab again
- // here.
- if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) ||
- event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
- (event.keyCode == 32 && event.shiftKey && this.options.tabMode == "default"))
- event.stop();
- else if (electric && electric.indexOf(event.character) != -1)
- this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
- else if ((event.character == "v" || event.character == "V")
- && (event.ctrlKey || event.metaKey) && !event.altKey) // ctrl-V
- this.reroutePasteEvent();
- },
-
- // Mark the node at the cursor dirty when a non-safe key is
- // released.
- keyUp: function(event) {
- this.cursorActivity(isSafeKey(event.keyCode));
- },
-
- // Indent the line following a given , or null for the first
- // line. If given a element, this must have been highlighted
- // so that it has an indentation method. Returns the whitespace
- // element that has been modified or created (if any).
- indentLineAfter: function(start, direction) {
- // whiteSpace is the whitespace span at the start of the line,
- // or null if there is no such node.
- var whiteSpace = start ? start.nextSibling : this.container.firstChild;
- if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
- whiteSpace = null;
-
- // Sometimes the start of the line can influence the correct
- // indentation, so we retrieve it.
- var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
- var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
-
- // Ask the lexical context for the correct indentation, and
- // compute how much this differs from the current indentation.
- var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
- if (direction != null && this.options.tabMode == "shift")
- newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
- else if (start)
- newIndent = start.indentation(nextChars, curIndent, direction);
- else if (Editor.Parser.firstIndentation)
- newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
- var indentDiff = newIndent - curIndent;
-
- // If there is too much, this is just a matter of shrinking a span.
- if (indentDiff < 0) {
- if (newIndent == 0) {
- if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild, 0);
- removeElement(whiteSpace);
- whiteSpace = null;
- }
- else {
- select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
- whiteSpace.currentText = makeWhiteSpace(newIndent);
- whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
- }
- }
- // Not enough...
- else if (indentDiff > 0) {
- // If there is whitespace, we grow it.
- if (whiteSpace) {
- whiteSpace.currentText = makeWhiteSpace(newIndent);
- whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
- }
- // Otherwise, we have to add a new whitespace node.
- else {
- whiteSpace = makePartSpan(makeWhiteSpace(newIndent), this.doc);
- whiteSpace.className = "whitespace";
- if (start) insertAfter(whiteSpace, start);
- else this.container.insertBefore(whiteSpace, this.container.firstChild);
- }
- if (firstText) select.snapshotMove(firstText.firstChild, whiteSpace.firstChild, curIndent, false, true);
- }
- if (indentDiff != 0) this.addDirtyNode(start);
- return whiteSpace;
- },
-
- // Re-highlight the selected part of the document.
- highlightAtCursor: function() {
- var pos = select.selectionTopNode(this.container, true);
- var to = select.selectionTopNode(this.container, false);
- if (pos === false || to === false) return;
-
- select.markSelection(this.win);
- if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
- return false;
- select.selectMarked();
- return true;
- },
-
- // When tab is pressed with text selected, the whole selection is
- // re-indented, when nothing is selected, the line with the cursor
- // is re-indented.
- handleTab: function(direction) {
- if (this.options.tabMode == "spaces")
- select.insertTabAtCursor(this.win);
- else
- this.reindentSelection(direction);
- },
-
- home: function() {
- var cur = select.selectionTopNode(this.container, true), start = cur;
- if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
- return false;
-
- while (cur && !isBR(cur)) cur = cur.previousSibling;
- var next = cur ? cur.nextSibling : this.container.firstChild;
- if (next && next != start && next.isPart && hasClass(next, "whitespace"))
- select.focusAfterNode(next, this.container);
- else
- select.focusAfterNode(cur, this.container);
-
- select.scrollToCursor(this.container);
- return true;
- },
-
- // Delay (or initiate) the next paren blink event.
- scheduleParenBlink: function() {
- if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
- var self = this;
- this.parenEvent = this.parent.setTimeout(function(){self.blinkParens();}, 300);
- },
-
- // Take the token before the cursor. If it contains a character in
- // '()[]{}', search for the matching paren/brace/bracket, and
- // highlight them in green for a moment, or red if no proper match
- // was found.
- blinkParens: function(jump) {
- if (!window.select) return;
- // Clear the event property.
- if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
- this.parenEvent = null;
-
- // Extract a 'paren' from a piece of text.
- function paren(node) {
- if (node.currentText) {
- var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
- return match && match[1];
- }
- }
- // Determine the direction a paren is facing.
- function forward(ch) {
- return /[\(\[\{]/.test(ch);
- }
-
- var ch, self = this, cursor = select.selectionTopNode(this.container, true);
- if (!cursor || !this.highlightAtCursor()) return;
- cursor = select.selectionTopNode(this.container, true);
- if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
- return;
- // We only look for tokens with the same className.
- var className = cursor.className, dir = forward(ch), match = matching[ch];
-
- // Since parts of the document might not have been properly
- // highlighted, and it is hard to know in advance which part we
- // have to scan, we just try, and when we find dirty nodes we
- // abort, parse them, and re-try.
- function tryFindMatch() {
- var stack = [], ch, ok = true;;
- for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
- if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
- if (forward(ch) == dir)
- stack.push(ch);
- else if (!stack.length)
- ok = false;
- else if (stack.pop() != matching[ch])
- ok = false;
- if (!stack.length) break;
- }
- else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
- return {node: runner, status: "dirty"};
- }
- }
- return {node: runner, status: runner && ok};
- }
- // Temporarily give the relevant nodes a colour.
- function blink(node, ok) {
- node.style.fontWeight = "bold";
- node.style.color = ok ? "#8F8" : "#F88";
- self.parent.setTimeout(function() {node.style.fontWeight = ""; node.style.color = "";}, 500);
- }
-
- while (true) {
- var found = tryFindMatch();
- if (found.status == "dirty") {
- this.highlight(found.node, endOfLine(found.node));
- // Needed because in some corner cases a highlight does not
- // reach a node.
- found.node.dirty = false;
- continue;
- }
- else {
- blink(cursor, found.status);
- if (found.node) {
- blink(found.node, found.status);
- if (jump) select.focusAfterNode(found.node.previousSibling, this.container);
- }
- break;
- }
- }
- },
-
- // Adjust the amount of whitespace at the start of the line that
- // the cursor is on so that it is indented properly.
- indentAtCursor: function(direction) {
- if (!this.container.firstChild) return;
- // The line has to have up-to-date lexical information, so we
- // highlight it first.
- if (!this.highlightAtCursor()) return;
- var cursor = select.selectionTopNode(this.container, false);
- // If we couldn't determine the place of the cursor,
- // there's nothing to indent.
- if (cursor === false)
- return;
- var lineStart = startOfLine(cursor);
- var whiteSpace = this.indentLineAfter(lineStart, direction);
- if (cursor == lineStart && whiteSpace)
- cursor = whiteSpace;
- // This means the indentation has probably messed up the cursor.
- if (cursor == whiteSpace)
- select.focusAfterNode(cursor, this.container);
- },
-
- // Indent all lines whose start falls inside of the current
- // selection.
- indentRegion: function(start, end, direction) {
- var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
- if (!isBR(end)) end = endOfLine(end, this.container);
-
- do {
- var next = endOfLine(current, this.container);
- if (current) this.highlight(before, next, true);
- this.indentLineAfter(current, direction);
- before = current;
- current = next;
- } while (current != end);
- select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
- },
-
- // Find the node that the cursor is in, mark it as dirty, and make
- // sure a highlight pass is scheduled.
- cursorActivity: function(safe) {
- if (internetExplorer) {
- this.container.createTextRange().execCommand("unlink");
- this.selectionSnapshot = select.selectionCoords(this.win);
- }
-
- var activity = this.options.cursorActivity;
- if (!safe || activity) {
- var cursor = select.selectionTopNode(this.container, false);
- if (cursor === false || !this.container.firstChild) return;
- cursor = cursor || this.container.firstChild;
- if (activity) activity(cursor);
- if (!safe) {
- this.scheduleHighlight();
- this.addDirtyNode(cursor);
- }
- }
- },
-
- reparseBuffer: function() {
- forEach(this.container.childNodes, function(node) {node.dirty = true;});
- if (this.container.firstChild)
- this.addDirtyNode(this.container.firstChild);
- },
-
- // Add a node to the set of dirty nodes, if it isn't already in
- // there.
- addDirtyNode: function(node) {
- node = node || this.container.firstChild;
- if (!node) return;
-
- for (var i = 0; i < this.dirty.length; i++)
- if (this.dirty[i] == node) return;
-
- if (node.nodeType != 3)
- node.dirty = true;
- this.dirty.push(node);
- },
-
- // Cause a highlight pass to happen in options.passDelay
- // milliseconds. Clear the existing timeout, if one exists. This
- // way, the passes do not happen while the user is typing, and
- // should as unobtrusive as possible.
- scheduleHighlight: function() {
- // Timeouts are routed through the parent window, because on
- // some browsers designMode windows do not fire timeouts.
- var self = this;
- this.parent.clearTimeout(this.highlightTimeout);
- this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
- },
-
- // Fetch one dirty node, and remove it from the dirty set.
- getDirtyNode: function() {
- while (this.dirty.length > 0) {
- var found = this.dirty.pop();
- // IE8 sometimes throws an unexplainable 'invalid argument'
- // exception for found.parentNode
- try {
- // If the node has been coloured in the meantime, or is no
- // longer in the document, it should not be returned.
- while (found && found.parentNode != this.container)
- found = found.parentNode
- if (found && (found.dirty || found.nodeType == 3))
- return found;
- } catch (e) {}
- }
- return null;
- },
-
- // Pick dirty nodes, and highlight them, until options.passTime
- // milliseconds have gone by. The highlight method will continue
- // to next lines as long as it finds dirty nodes. It returns
- // information about the place where it stopped. If there are
- // dirty nodes left after this function has spent all its lines,
- // it shedules another highlight to finish the job.
- highlightDirty: function(force) {
- // Prevent FF from raising an error when it is firing timeouts
- // on a page that's no longer loaded.
- if (!window.select) return;
-
- if (!this.options.readOnly) select.markSelection(this.win);
- var start, endTime = force ? null : time() + this.options.passTime;
- while ((time() < endTime || force) && (start = this.getDirtyNode())) {
- var result = this.highlight(start, endTime);
- if (result && result.node && result.dirty)
- this.addDirtyNode(result.node);
- }
- if (!this.options.readOnly) select.selectMarked();
- if (start) this.scheduleHighlight();
- return this.dirty.length == 0;
- },
-
- // Creates a function that, when called through a timeout, will
- // continuously re-parse the document.
- documentScanner: function(passTime) {
- var self = this, pos = null;
- return function() {
- // FF timeout weirdness workaround.
- if (!window.select) return;
- // If the current node is no longer in the document... oh
- // well, we start over.
- if (pos && pos.parentNode != self.container)
- pos = null;
- select.markSelection(self.win);
- var result = self.highlight(pos, time() + passTime, true);
- select.selectMarked();
- var newPos = result ? (result.node && result.node.nextSibling) : null;
- pos = (pos == newPos) ? null : newPos;
- self.delayScanning();
- };
- },
-
- // Starts the continuous scanning process for this document after
- // a given interval.
- delayScanning: function() {
- if (this.scanner) {
- this.parent.clearTimeout(this.documentScan);
- this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
- }
- },
-
- // The function that does the actual highlighting/colouring (with
- // help from the parser and the DOM normalizer). Its interface is
- // rather overcomplicated, because it is used in different
- // situations: ensuring that a certain line is highlighted, or
- // highlighting up to X milliseconds starting from a certain
- // point. The 'from' argument gives the node at which it should
- // start. If this is null, it will start at the beginning of the
- // document. When a timestamp is given with the 'target' argument,
- // it will stop highlighting at that time. If this argument holds
- // a DOM node, it will highlight until it reaches that node. If at
- // any time it comes across two 'clean' lines (no dirty nodes), it
- // will stop, except when 'cleanLines' is true. maxBacktrack is
- // the maximum number of lines to backtrack to find an existing
- // parser instance. This is used to give up in situations where a
- // highlight would take too long and freeze the browser interface.
- highlight: function(from, target, cleanLines, maxBacktrack){
- var container = this.container, self = this, active = this.options.activeTokens;
- var endTime = (typeof target == "number" ? target : null);
-
- if (!container.firstChild)
- return;
- // Backtrack to the first node before from that has a partial
- // parse stored.
- while (from && (!from.parserFromHere || from.dirty)) {
- if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
- return false;
- from = from.previousSibling;
- }
- // If we are at the end of the document, do nothing.
- if (from && !from.nextSibling)
- return;
-
- // Check whether a part ( node) and the corresponding token
- // match.
- function correctPart(token, part){
- return !part.reduced && part.currentText == token.value && part.className == token.style;
- }
- // Shorten the text associated with a part by chopping off
- // characters from the front. Note that only the currentText
- // property gets changed. For efficiency reasons, we leave the
- // nodeValue alone -- we set the reduced flag to indicate that
- // this part must be replaced.
- function shortenPart(part, minus){
- part.currentText = part.currentText.substring(minus);
- part.reduced = true;
- }
- // Create a part corresponding to a given token.
- function tokenPart(token){
- var part = makePartSpan(token.value, self.doc);
- part.className = token.style;
- return part;
- }
-
- function maybeTouch(node) {
- if (node) {
- var old = node.oldNextSibling;
- if (lineDirty || old === undefined || node.nextSibling != old)
- self.history.touch(node);
- node.oldNextSibling = node.nextSibling;
- }
- else {
- var old = self.container.oldFirstChild;
- if (lineDirty || old === undefined || self.container.firstChild != old)
- self.history.touch(null);
- self.container.oldFirstChild = self.container.firstChild;
- }
- }
-
- // Get the token stream. If from is null, we start with a new
- // parser from the start of the frame, otherwise a partial parse
- // is resumed.
- var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
- stream = stringStream(traversal),
- parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
-
- // parts is an interface to make it possible to 'delay' fetching
- // the next DOM node until we are completely done with the one
- // before it. This is necessary because often the next node is
- // not yet available when we want to proceed past the current
- // one.
- var parts = {
- current: null,
- // Fetch current node.
- get: function(){
- if (!this.current)
- this.current = traversal.nodes.shift();
- return this.current;
- },
- // Advance to the next part (do not fetch it yet).
- next: function(){
- this.current = null;
- },
- // Remove the current part from the DOM tree, and move to the
- // next.
- remove: function(){
- container.removeChild(this.get());
- this.current = null;
- },
- // Advance to the next part that is not empty, discarding empty
- // parts.
- getNonEmpty: function(){
- var part = this.get();
- // Allow empty nodes when they are alone on a line, needed
- // for the FF cursor bug workaround (see select.js,
- // insertNewlineAtCursor).
- while (part && isSpan(part) && part.currentText == "") {
- var old = part;
- this.remove();
- part = this.get();
- // Adjust selection information, if any. See select.js for details.
- select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
- }
- return part;
- }
- };
-
- var lineDirty = false, prevLineDirty = true, lineNodes = 0;
-
- // This forEach loops over the tokens from the parsed stream, and
- // at the same time uses the parts object to proceed through the
- // corresponding DOM nodes.
- forEach(parsed, function(token){
- var part = parts.getNonEmpty();
-
- if (token.value == "\n"){
- // The idea of the two streams actually staying synchronized
- // is such a long shot that we explicitly check.
- if (!isBR(part))
- throw "Parser out of sync. Expected BR.";
-
- if (part.dirty || !part.indentation) lineDirty = true;
- maybeTouch(from);
- from = part;
-
- // Every gets a copy of the parser state and a lexical
- // context assigned to it. The first is used to be able to
- // later resume parsing from this point, the second is used
- // for indentation.
- part.parserFromHere = parsed.copy();
- part.indentation = token.indentation;
- part.dirty = false;
-
- // If the target argument wasn't an integer, go at least
- // until that node.
- if (endTime == null && part == target) throw StopIteration;
-
- // A clean line with more than one node means we are done.
- // Throwing a StopIteration is the way to break out of a
- // MochiKit forEach loop.
- if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
- throw StopIteration;
- prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
- parts.next();
- }
- else {
- if (!isSpan(part))
- throw "Parser out of sync. Expected SPAN.";
- if (part.dirty)
- lineDirty = true;
- lineNodes++;
-
- // If the part matches the token, we can leave it alone.
- if (correctPart(token, part)){
- part.dirty = false;
- parts.next();
- }
- // Otherwise, we have to fix it.
- else {
- lineDirty = true;
- // Insert the correct part.
- var newPart = tokenPart(token);
- container.insertBefore(newPart, part);
- if (active) active(newPart, token, self);
- var tokensize = token.value.length;
- var offset = 0;
- // Eat up parts until the text for this token has been
- // removed, adjusting the stored selection info (see
- // select.js) in the process.
- while (tokensize > 0) {
- part = parts.get();
- var partsize = part.currentText.length;
- select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
- if (partsize > tokensize){
- shortenPart(part, tokensize);
- tokensize = 0;
- }
- else {
- tokensize -= partsize;
- offset += partsize;
- parts.remove();
- }
- }
- }
- }
- });
- maybeTouch(from);
- webkitLastLineHack(this.container);
-
- // The function returns some status information that is used by
- // hightlightDirty to determine whether and where it has to
- // continue.
- return {node: parts.getNonEmpty(),
- dirty: lineDirty};
- }
- };
-
- return Editor;
-})();
-
-addEventHandler(window, "load", function() {
- var CodeMirror = window.frameElement.CodeMirror;
- CodeMirror.editor = new Editor(CodeMirror.options);
- this.parent.setTimeout(method(CodeMirror, "init"), 0);
-});
-
-;;;;
-
-// A framework for simple tokenizers. Takes care of newlines and
-// white-space, and of getting the text from the source stream into
-// the token object. A state is a function of two arguments -- a
-// string stream and a setState function. The second can be used to
-// change the tokenizer's state, and can be ignored for stateless
-// tokenizers. This function should advance the stream over a token
-// and return a string or object containing information about the next
-// token, or null to pass and have the (new) state be called to finish
-// the token. When a string is given, it is wrapped in a {style, type}
-// object. In the resulting object, the characters consumed are stored
-// under the content property. Any whitespace following them is also
-// automatically consumed, and added to the value property. (Thus,
-// content is the actual meaningful part of the token, while value
-// contains all the text it spans.)
-
-function tokenizer(source, state) {
- // Newlines are always a separate token.
- function isWhiteSpace(ch) {
- // The messy regexp is because IE's regexp matcher is of the
- // opinion that non-breaking spaces are no whitespace.
- return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
- }
-
- var tokenizer = {
- state: state,
-
- take: function(type) {
- if (typeof(type) == "string")
- type = {style: type, type: type};
-
- type.content = (type.content || "") + source.get();
- if (!/\n$/.test(type.content))
- source.nextWhile(isWhiteSpace);
- type.value = type.content + source.get();
- return type;
- },
-
- next: function () {
- if (!source.more()) throw StopIteration;
-
- var type;
- if (source.equals("\n")) {
- source.next();
- return this.take("whitespace");
- }
-
- if (source.applies(isWhiteSpace))
- type = "whitespace";
- else
- while (!type)
- type = this.state(source, function(s) {tokenizer.state = s;});
-
- return this.take(type);
- }
- };
- return tokenizer;
-}
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/codemirror.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/codemirror.js
deleted file mode 100644
index 341ee3a4c7..0000000000
--- a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/codemirror.js
+++ /dev/null
@@ -1,582 +0,0 @@
-/* CodeMirror main module (http://codemirror.net/)
- *
- * Implements the CodeMirror constructor and prototype, which take care
- * of initializing the editor frame, and providing the outside interface.
- */
-
-// The CodeMirrorConfig object is used to specify a default
-// configuration. If you specify such an object before loading this
-// file, the values you put into it will override the defaults given
-// below. You can also assign to it after loading.
-var CodeMirrorConfig = window.CodeMirrorConfig || {};
-
-var CodeMirror = (function(){
- function setDefaults(object, defaults) {
- for (var option in defaults) {
- if (!object.hasOwnProperty(option))
- object[option] = defaults[option];
- }
- }
- function forEach(array, action) {
- for (var i = 0; i < array.length; i++)
- action(array[i]);
- }
- function createHTMLElement(el) {
- if (document.createElementNS && document.documentElement.namespaceURI !== null)
- return document.createElementNS("http://www.w3.org/1999/xhtml", el)
- else
- return document.createElement(el)
- }
-
- // These default options can be overridden by passing a set of
- // options to a specific CodeMirror constructor. See manual.html for
- // their meaning.
- setDefaults(CodeMirrorConfig, {
- stylesheet: [],
- path: "",
- parserfile: [],
- basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
- iframeClass: null,
- passDelay: 200,
- passTime: 50,
- lineNumberDelay: 200,
- lineNumberTime: 50,
- continuousScanning: false,
- saveFunction: null,
- onLoad: null,
- onChange: null,
- undoDepth: 50,
- undoDelay: 800,
- disableSpellcheck: true,
- textWrapping: true,
- readOnly: false,
- width: "",
- height: "300px",
- minHeight: 100,
- autoMatchParens: false,
- markParen: null,
- unmarkParen: null,
- parserConfig: null,
- tabMode: "indent", // or "spaces", "default", "shift"
- enterMode: "indent", // or "keep", "flat"
- electricChars: true,
- reindentOnLoad: false,
- activeTokens: null,
- onCursorActivity: null,
- lineNumbers: false,
- firstLineNumber: 1,
- onLineNumberClick: null,
- indentUnit: 2,
- domain: null,
- noScriptCaching: false,
- incrementalLoading: false
- });
-
- function addLineNumberDiv(container, firstNum) {
- var nums = createHTMLElement("div"),
- scroller = createHTMLElement("div");
- nums.style.position = "absolute";
- nums.style.height = "100%";
- if (nums.style.setExpression) {
- try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");}
- catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions
- }
- nums.style.top = "0px";
- nums.style.left = "0px";
- nums.style.overflow = "hidden";
- container.appendChild(nums);
- scroller.className = "CodeMirror-line-numbers";
- nums.appendChild(scroller);
- scroller.innerHTML = "
" + firstNum + "
";
- return nums;
- }
-
- function frameHTML(options) {
- if (typeof options.parserfile == "string")
- options.parserfile = [options.parserfile];
- if (typeof options.basefiles == "string")
- options.basefiles = [options.basefiles];
- if (typeof options.stylesheet == "string")
- options.stylesheet = [options.stylesheet];
-
- var sp = " spellcheck=\"" + (options.disableSpellcheck ? "false" : "true") + "\"";
- var html = [""];
- // Hack to work around a bunch of IE8-specific problems.
- html.push("");
- var queryStr = options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : "";
- forEach(options.stylesheet, function(file) {
- html.push("");
- });
- forEach(options.basefiles.concat(options.parserfile), function(file) {
- if (!/^https?:/.test(file)) file = options.path + file;
- html.push("]*>|$)", "i"),
+ modeExt: CodeMirror.modeExtensions["javascript"],
+ modeName: "javascript"
+ };
+
+ var lastCharPos = (typeof (absPos) !== "undefined" ? absPos : text.length - 1);
+ // Detect modes for the entire text
+ for (var i = 0; i < modeMatchers.length; i++) {
+ var curPos = 0;
+ while (curPos <= lastCharPos) {
+ var m = text.substr(curPos).match(modeMatchers[i].regex);
+ if (m != null) {
+ if (m.length > 1 && m[1].length > 0) {
+ // Push block begin pos
+ var blockBegin = curPos + m.index + m[0].indexOf(m[1]);
+ modeInfos.push(
+ {
+ pos: blockBegin,
+ modeExt: modeMatchers[i].modeExt,
+ modeName: modeMatchers[i].modeName
+ });
+ // Push block end pos
+ modeInfos.push(
+ {
+ pos: blockBegin + m[1].length,
+ modeExt: modeInfos[0].modeExt,
+ modeName: modeInfos[0].modeName
+ });
+ curPos += m.index + m[0].length;
+ continue;
+ }
+ else {
+ curPos += m.index + Math.max(m[0].length, 1);
+ }
+ }
+ else { // No more matches
+ break;
+ }
+ }
+ }
+ // Sort mode infos
+ modeInfos.sort(function sortModeInfo(a, b) {
+ return a.pos - b.pos;
+ });
+
+ return modeInfos;
+ },
+
+ autoFormatLineBreaks: function (text, startPos, endPos) {
+ var modeInfos = this.getModeInfos(text);
+ var reBlockStartsWithNewline = new RegExp("^\\s*?\n");
+ var reBlockEndsWithNewline = new RegExp("\n\\s*?$");
+ var res = "";
+ // Use modes info to break lines correspondingly
+ if (modeInfos.length > 1) { // Deal with multi-mode text
+ for (var i = 1; i <= modeInfos.length; i++) {
+ var selStart = modeInfos[i - 1].pos;
+ var selEnd = (i < modeInfos.length ? modeInfos[i].pos : endPos);
+
+ if (selStart >= endPos) { // The block starts later than the needed fragment
+ break;
+ }
+ if (selStart < startPos) {
+ if (selEnd <= startPos) { // The block starts earlier than the needed fragment
+ continue;
+ }
+ selStart = startPos;
+ }
+ if (selEnd > endPos) {
+ selEnd = endPos;
+ }
+ var textPortion = text.substring(selStart, selEnd);
+ if (modeInfos[i - 1].modeName != "xml") { // Starting a CSS or JavaScript block
+ if (!reBlockStartsWithNewline.test(textPortion)
+ && selStart > 0) { // The block does not start with a line break
+ textPortion = "\n" + textPortion;
+ }
+ if (!reBlockEndsWithNewline.test(textPortion)
+ && selEnd < text.length - 1) { // The block does not end with a line break
+ textPortion += "\n";
+ }
+ }
+ res += modeInfos[i - 1].modeExt.autoFormatLineBreaks(textPortion);
+ }
+ }
+ else { // Single-mode text
+ res = modeInfos[0].modeExt.autoFormatLineBreaks(text.substring(startPos, endPos));
+ }
+
+ return res;
+ }
+};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/javascript-hint.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/javascript-hint.js
new file mode 100644
index 0000000000..2117e5af14
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/javascript-hint.js
@@ -0,0 +1,134 @@
+(function () {
+ function forEach(arr, f) {
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+ }
+
+ function arrayContains(arr, item) {
+ if (!Array.prototype.indexOf) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === item) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return arr.indexOf(item) != -1;
+ }
+
+ function scriptHint(editor, keywords, getToken) {
+ // Find the token at the cursor
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
+ // If it's not a 'word-style' token, ignore the token.
+ if (!/^[\w$_]*$/.test(token.string)) {
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+ className: token.string == "." ? "property" : null};
+ }
+ // If it is a property, find out what it is a property of.
+ while (tprop.className == "property") {
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
+ if (tprop.string != ".") return;
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
+ if (tprop.string == ')') {
+ var level = 1;
+ do {
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
+ switch (tprop.string) {
+ case ')': level++; break;
+ case '(': level--; break;
+ default: break;
+ }
+ } while (level > 0)
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
+ if (tprop.className == 'variable')
+ tprop.className = 'function';
+ else return; // no clue
+ }
+ if (!context) var context = [];
+ context.push(tprop);
+ }
+ return {list: getCompletions(token, context, keywords),
+ from: {line: cur.line, ch: token.start},
+ to: {line: cur.line, ch: token.end}};
+ }
+
+ CodeMirror.javascriptHint = function(editor) {
+ return scriptHint(editor, javascriptKeywords,
+ function (e, cur) {return e.getTokenAt(cur);});
+ }
+
+ function getCoffeeScriptToken(editor, cur) {
+ // This getToken, it is for coffeescript, imitates the behavior of
+ // getTokenAt method in javascript.js, that is, returning "property"
+ // type and treat "." as indepenent token.
+ var token = editor.getTokenAt(cur);
+ if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
+ token.end = token.start;
+ token.string = '.';
+ token.className = "property";
+ }
+ else if (/^\.[\w$_]*$/.test(token.string)) {
+ token.className = "property";
+ token.start++;
+ token.string = token.string.replace(/\./, '');
+ }
+ return token;
+ }
+
+ CodeMirror.coffeescriptHint = function(editor) {
+ return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken);
+ }
+
+ var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
+ "toUpperCase toLowerCase split concat match replace search").split(" ");
+ var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
+ "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
+ var funcProps = "prototype apply call bind".split(" ");
+ var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
+ "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
+ var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
+ "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
+
+ function getCompletions(token, context, keywords) {
+ var found = [], start = token.string;
+ function maybeAdd(str) {
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
+ }
+ function gatherCompletions(obj) {
+ if (typeof obj == "string") forEach(stringProps, maybeAdd);
+ else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
+ else if (obj instanceof Function) forEach(funcProps, maybeAdd);
+ for (var name in obj) maybeAdd(name);
+ }
+
+ if (context) {
+ // If this is a property, see if it belongs to some object we can
+ // find in the current environment.
+ var obj = context.pop(), base;
+ if (obj.className == "variable")
+ base = window[obj.string];
+ else if (obj.className == "string")
+ base = "";
+ else if (obj.className == "atom")
+ base = 1;
+ else if (obj.className == "function") {
+ if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
+ (typeof window.jQuery == 'function'))
+ base = window.jQuery();
+ else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
+ base = window._();
+ }
+ while (base != null && context.length)
+ base = base[context.pop().string];
+ if (base != null) gatherCompletions(base);
+ }
+ else {
+ // If not, just look in the window object and any local scope
+ // (reading into JS mode internals to get at the local variables)
+ for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
+ gatherCompletions(window);
+ forEach(keywords, maybeAdd);
+ }
+ return found;
+ }
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/loadmode.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/loadmode.js
new file mode 100644
index 0000000000..48d5a7abf2
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/loadmode.js
@@ -0,0 +1,51 @@
+(function() {
+ if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
+
+ var loading = {};
+ function splitCallback(cont, n) {
+ var countDown = n;
+ return function() { if (--countDown == 0) cont(); }
+ }
+ function ensureDeps(mode, cont) {
+ var deps = CodeMirror.modes[mode].dependencies;
+ if (!deps) return cont();
+ var missing = [];
+ for (var i = 0; i < deps.length; ++i) {
+ if (!CodeMirror.modes.hasOwnProperty(deps[i]))
+ missing.push(deps[i]);
+ }
+ if (!missing.length) return cont();
+ var split = splitCallback(cont, missing.length);
+ for (var i = 0; i < missing.length; ++i)
+ CodeMirror.requireMode(missing[i], split);
+ }
+
+ CodeMirror.requireMode = function(mode, cont) {
+ if (typeof mode != "string") mode = mode.name;
+ if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
+ if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
+
+ var script = document.createElement("script");
+ script.src = CodeMirror.modeURL.replace(/%N/g, mode);
+ var others = document.getElementsByTagName("script")[0];
+ others.parentNode.insertBefore(script, others);
+ var list = loading[mode] = [cont];
+ var count = 0, poll = setInterval(function() {
+ if (++count > 100) return clearInterval(poll);
+ if (CodeMirror.modes.hasOwnProperty(mode)) {
+ clearInterval(poll);
+ loading[mode] = null;
+ ensureDeps(mode, function() {
+ for (var i = 0; i < list.length; ++i) list[i]();
+ });
+ }
+ }, 200);
+ };
+
+ CodeMirror.autoLoadMode = function(instance, mode) {
+ if (!CodeMirror.modes.hasOwnProperty(mode))
+ CodeMirror.requireMode(mode, function() {
+ instance.setOption("mode", instance.getOption("mode"));
+ });
+ };
+}());
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/match-highlighter.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/match-highlighter.js
new file mode 100644
index 0000000000..59098ff86c
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/match-highlighter.js
@@ -0,0 +1,44 @@
+// Define match-highlighter commands. Depends on searchcursor.js
+// Use by attaching the following function call to the onCursorActivity event:
+ //myCodeMirror.matchHighlight(minChars);
+// And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html)
+
+(function() {
+ var DEFAULT_MIN_CHARS = 2;
+
+ function MatchHighlightState() {
+ this.marked = [];
+ }
+ function getMatchHighlightState(cm) {
+ return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState());
+ }
+
+ function clearMarks(cm) {
+ var state = getMatchHighlightState(cm);
+ for (var i = 0; i < state.marked.length; ++i)
+ state.marked[i].clear();
+ state.marked = [];
+ }
+
+ function markDocument(cm, className, minChars) {
+ clearMarks(cm);
+ minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS);
+ if (cm.somethingSelected() && cm.getSelection().replace(/^\s+|\s+$/g, "").length >= minChars) {
+ var state = getMatchHighlightState(cm);
+ var query = cm.getSelection();
+ cm.operation(function() {
+ if (cm.lineCount() < 2000) { // This is too expensive on big documents.
+ for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
+ //Only apply matchhighlight to the matches other than the one actually selected
+ if (!(cursor.from().line === cm.getCursor(true).line && cursor.from().ch === cm.getCursor(true).ch))
+ state.marked.push(cm.markText(cursor.from(), cursor.to(), className));
+ }
+ }
+ });
+ }
+ }
+
+ CodeMirror.defineExtension("matchHighlight", function(className, minChars) {
+ markDocument(this, className, minChars);
+ });
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/multiplex.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/multiplex.js
new file mode 100644
index 0000000000..c8bb1e9785
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/multiplex.js
@@ -0,0 +1,81 @@
+CodeMirror.multiplexingMode = function(outer /*, others */) {
+ // Others should be {open, close, mode [, delimStyle]} objects
+ var others = Array.prototype.slice.call(arguments, 1);
+ var n_others = others.length;
+
+ function indexOf(string, pattern, from) {
+ if (typeof pattern == "string") return string.indexOf(pattern, from);
+ var m = pattern.exec(from ? string.slice(from) : string);
+ return m ? m.index + from : -1;
+ }
+
+ return {
+ startState: function() {
+ return {
+ outer: CodeMirror.startState(outer),
+ innerActive: null,
+ inner: null
+ };
+ },
+
+ copyState: function(state) {
+ return {
+ outer: CodeMirror.copyState(outer, state.outer),
+ innerActive: state.innerActive,
+ inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
+ };
+ },
+
+ token: function(stream, state) {
+ if (!state.innerActive) {
+ var cutOff = Infinity, oldContent = stream.string;
+ for (var i = 0; i < n_others; ++i) {
+ var other = others[i];
+ var found = indexOf(oldContent, other.open, stream.pos);
+ if (found == stream.pos) {
+ stream.match(other.open);
+ state.innerActive = other;
+ state.inner = CodeMirror.startState(other.mode, outer.indent(state.outer, ""));
+ return other.delimStyle;
+ } else if (found != -1 && found < cutOff) {
+ cutOff = found;
+ }
+ }
+ if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
+ var outerToken = outer.token(stream, state.outer);
+ if (cutOff != Infinity) stream.string = oldContent;
+ return outerToken;
+ } else {
+ var curInner = state.innerActive, oldContent = stream.string;
+ var found = indexOf(oldContent, curInner.close, stream.pos);
+ if (found == stream.pos) {
+ stream.match(curInner.close);
+ state.innerActive = state.inner = null;
+ return curInner.delimStyle;
+ }
+ if (found > -1) stream.string = oldContent.slice(0, found);
+ var innerToken = curInner.mode.token(stream, state.inner);
+ if (found > -1) stream.string = oldContent;
+ var cur = stream.current(), found = cur.indexOf(curInner.close);
+ if (found > -1) stream.backUp(cur.length - found);
+ return innerToken;
+ }
+ },
+
+ indent: function(state, textAfter) {
+ var mode = state.innerActive ? state.innerActive.mode : outer;
+ if (!mode.indent) return CodeMirror.Pass;
+ return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
+ },
+
+ compareStates: function(a, b) {
+ if (a.innerActive != b.innerActive) return false;
+ var mode = a.innerActive || outer;
+ if (!mode.compareStates) return CodeMirror.Pass;
+ return mode.compareStates(a.innerActive ? a.inner : a.outer,
+ b.innerActive ? b.inner : b.outer);
+ },
+
+ electricChars: outer.electricChars
+ };
+};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/overlay.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/overlay.js
new file mode 100644
index 0000000000..1d5df6c64c
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/overlay.js
@@ -0,0 +1,52 @@
+// Utility function that allows modes to be combined. The mode given
+// as the base argument takes care of most of the normal mode
+// functionality, but a second (typically simple) mode is used, which
+// can override the style of text. Both modes get to parse all of the
+// text, but when both assign a non-null style to a piece of code, the
+// overlay wins, unless the combine argument was true, in which case
+// the styles are combined.
+
+// overlayParser is the old, deprecated name
+CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
+ return {
+ startState: function() {
+ return {
+ base: CodeMirror.startState(base),
+ overlay: CodeMirror.startState(overlay),
+ basePos: 0, baseCur: null,
+ overlayPos: 0, overlayCur: null
+ };
+ },
+ copyState: function(state) {
+ return {
+ base: CodeMirror.copyState(base, state.base),
+ overlay: CodeMirror.copyState(overlay, state.overlay),
+ basePos: state.basePos, baseCur: null,
+ overlayPos: state.overlayPos, overlayCur: null
+ };
+ },
+
+ token: function(stream, state) {
+ if (stream.start == state.basePos) {
+ state.baseCur = base.token(stream, state.base);
+ state.basePos = stream.pos;
+ }
+ if (stream.start == state.overlayPos) {
+ stream.pos = stream.start;
+ state.overlayCur = overlay.token(stream, state.overlay);
+ state.overlayPos = stream.pos;
+ }
+ stream.pos = Math.min(state.basePos, state.overlayPos);
+ if (stream.eol()) state.basePos = state.overlayPos = 0;
+
+ if (state.overlayCur == null) return state.baseCur;
+ if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
+ else return state.overlayCur;
+ },
+
+ indent: base.indent && function(state, textAfter) {
+ return base.indent(state.base, textAfter);
+ },
+ electricChars: base.electricChars
+ };
+};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/pig-hint.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/pig-hint.js
new file mode 100644
index 0000000000..aba1c5e282
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/pig-hint.js
@@ -0,0 +1,125 @@
+(function () {
+ function forEach(arr, f) {
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+ }
+
+ function arrayContains(arr, item) {
+ if (!Array.prototype.indexOf) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === item) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return arr.indexOf(item) != -1;
+ }
+
+ function scriptHint(editor, keywords, getToken) {
+ // Find the token at the cursor
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
+ // If it's not a 'word-style' token, ignore the token.
+
+ if (!/^[\w$_]*$/.test(token.string)) {
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+ className: token.string == ":" ? "pig-type" : null};
+ }
+
+ if (!context) var context = [];
+ context.push(tprop);
+
+ var completionList = getCompletions(token, context);
+ completionList = completionList.sort();
+ //prevent autocomplete for last word, instead show dropdown with one word
+ if(completionList.length == 1) {
+ completionList.push(" ");
+ }
+
+ return {list: completionList,
+ from: {line: cur.line, ch: token.start},
+ to: {line: cur.line, ch: token.end}};
+ }
+
+ CodeMirror.pigHint = function(editor) {
+ return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
+ }
+
+ function toTitleCase(str) {
+ return str.replace(/(?:^|\s)\w/g, function(match) {
+ return match.toUpperCase();
+ });
+ }
+
+ var pigKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
+ + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
+ + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
+ + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
+ + "NEQ MATCHES TRUE FALSE";
+ var pigKeywordsU = pigKeywords.split(" ");
+ var pigKeywordsL = pigKeywords.toLowerCase().split(" ");
+
+ var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP";
+ var pigTypesU = pigTypes.split(" ");
+ var pigTypesL = pigTypes.toLowerCase().split(" ");
+
+ var pigBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
+ + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
+ + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
+ + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
+ + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
+ + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
+ + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA "
+ + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
+ + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
+ + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER";
+
+ var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" ");
+ var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" ");
+
+ var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs "
+ + "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax "
+ + "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum "
+ + "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker "
+ + "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize "
+ + "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax "
+ + "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" ");
+
+ function getCompletions(token, context) {
+ var found = [], start = token.string;
+ function maybeAdd(str) {
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
+ }
+
+ function gatherCompletions(obj) {
+ if(obj == ":") {
+ forEach(pigTypesL, maybeAdd);
+ }
+ else {
+ forEach(pigBuiltinsU, maybeAdd);
+ forEach(pigBuiltinsL, maybeAdd);
+ forEach(pigBuiltinsC, maybeAdd);
+ forEach(pigTypesU, maybeAdd);
+ forEach(pigTypesL, maybeAdd);
+ forEach(pigKeywordsU, maybeAdd);
+ forEach(pigKeywordsL, maybeAdd);
+ }
+ }
+
+ if (context) {
+ // If this is a property, see if it belongs to some object we can
+ // find in the current environment.
+ var obj = context.pop(), base;
+
+ if (obj.className == "pig-word")
+ base = obj.string;
+ else if(obj.className == "pig-type")
+ base = ":" + obj.string;
+
+ while (base != null && context.length)
+ base = base[context.pop().string];
+ if (base != null) gatherCompletions(base);
+ }
+ return found;
+ }
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hint.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hint.js
new file mode 100644
index 0000000000..45f52f1a8e
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hint.js
@@ -0,0 +1,119 @@
+(function () {
+
+ CodeMirror.razorHints = [];
+
+
+ function arrayContains(arr, item) {
+ if (!Array.prototype.indexOf) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === item) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return arr.indexOf(item) != -1;
+ }
+
+
+ CodeMirror.razorHint = function (editor, char) {
+
+ if (char.length > 0) {
+ var cursor = editor.getCursor();
+ editor.replaceSelection(char);
+ cursor = { line: cursor.line, ch: cursor.ch + 1 };
+ editor.setCursor(cursor);
+ }
+
+ // dirty hack for simple-hint to receive getHint event on space
+ var getTokenAt = editor.getTokenAt;
+ editor.getTokenAt = function () { return 'disabled'; };
+ CodeMirror.simpleHint(editor, getHint);
+ editor.getTokenAt = getTokenAt;
+
+ //return scriptHint(editor, pigKeywordsU, char, function (e, cur) { return e.getTokenAt(cur); });
+ }
+
+ var getHint = function (cm) {
+
+ var cursor = cm.getCursor();
+ if (cursor.ch > 0) {
+
+ var text = cm.getRange({ line: 0, ch: 0 }, cursor);
+ var typed = '';
+ var simbol = '';
+
+ for (var i = text.length - 1; i >= 0; i--) {
+ if (text[i] == '@' || text[i] == '.') {
+ simbol = text[i];
+ break;
+ }
+ else {
+ typed = text[i] + typed;
+ }
+ }
+ }
+
+ text = text.slice(0, text.length - typed.length);
+
+ var hints = getCompletions(text, simbol, typed);
+ return {
+ list: hints,
+ from: { line: cursor.line, ch: cursor.ch - typed.length },
+ to: cursor
+ };
+ };
+
+ function searchHints(text, trigger, search) {
+ if (search == "") {
+ var hints = CodeMirror.razorHints[text];
+ if (typeof hints === 'undefined')
+ hints = CodeMirror.razorHints[simbol];
+
+ return hints;
+ } else {
+
+ }
+ }
+
+ function getCompletions(text, trigger, search) {
+ var found = [];
+
+ function maybeAdd(str) {
+ var match = str;
+ if (typeof match === 'string') {
+ match = [str, str];
+ }
+
+ if (search == "" && !arrayContains(found, match)) found.push(match);
+ else if (match[0].toLowerCase().indexOf(search) == 0 && !arrayContains(found, match)) found.push(match);
+ }
+
+ forEach(CodeMirror.razorHints[text], maybeAdd);
+ forEach(CodeMirror.razorHints[trigger], maybeAdd);
+
+ return found.sort(function (a, b) {
+ var nameA = a[0].toLowerCase(), nameB = b[0].toLowerCase()
+ if (nameA < nameB)
+ return -1
+ if (nameA > nameB)
+ return 1
+
+ return 0 //default return value (no sorting)
+ })
+ }
+
+ function forEach(arr, f) {
+ if (typeof arr != 'undefined')
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+ }
+
+
+ function toTitleCase(str) {
+ return str.replace(/(?:^|\s)\w/g, function (match) {
+ return match.toUpperCase();
+ });
+ }
+
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hints.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hints.js
new file mode 100644
index 0000000000..19bee60c85
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/razor-hints.js
@@ -0,0 +1,81 @@
+(function() {
+
+ CodeMirror.razorHints['@'] = [
+ 'inherits',
+ 'Library',
+ 'Model',
+ 'Parameter',
+ 'using',
+ 'Dictionary',
+ ['if/else', 'if(SomeCondition){\n\n}else{\n\n}\n'],
+ ['if', 'if(SomeCondition){\n\n}\n'],
+ ['foreach', 'foreach(var item in collection){\n\n}\n'],
+ ['context', 'inherits umbraco.MacroEngines.DynamicNodeContext\n\n'],
+ ['helper', 'helperMethod(Model)\n\n@helperMethod(dynamic val){\n\t
Hello @val.Name\n}\n\n'],
+ ];
+
+ CodeMirror.razorHints['.'] = [
+ 'Ancestors',
+ 'AncestorsOrSelf',
+ 'Children',
+ 'Descendants',
+ 'DescendantsOrSelf',
+ 'Parent',
+ 'First()',
+ 'Last()',
+ 'Up()',
+ 'Next()',
+ 'Previous()',
+ 'AncestorOrSelf()',
+ 'Where()',
+ 'OrderBy()',
+ 'GroupBy()',
+ 'InGroupsOf()',
+ 'Pluck()',
+ 'Take()',
+ 'Skip()',
+ 'Count()',
+ 'XPath()',
+ 'Search()',
+
+ 'Id',
+ 'Template',
+ 'SortOrder',
+ 'Name',
+ 'Visible',
+ 'Url',
+ 'UrlName',
+ 'NodeTypeAlias',
+ 'WriterName',
+ 'CreatorName',
+ 'WriterId',
+ 'CreatorId',
+ 'Path',
+ 'CreateDate',
+ 'UpdateDate',
+ 'NiceUrl',
+ 'Level',
+ ];
+
+ CodeMirror.razorHints['@Library.'] = [
+ 'Search()',
+ 'NodeById()',
+ ];
+
+ CodeMirror.razorHints['@Model.'] =
+ CodeMirror.razorHints['<'] =
+ CodeMirror.razorHints['<'] = [
+ 'second',
+ 'two'
+ ];
+
+ CodeMirror.razorHints['<'] = [
+ 'three',
+ 'x-three'
+ ];
+
+})();
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/runmode.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/runmode.js
new file mode 100644
index 0000000000..fc58d857d9
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/runmode.js
@@ -0,0 +1,49 @@
+CodeMirror.runMode = function(string, modespec, callback, options) {
+ var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
+ var isNode = callback.nodeType == 1;
+ var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
+ if (isNode) {
+ var node = callback, accum = [], col = 0;
+ callback = function(text, style) {
+ if (text == "\n") {
+ accum.push(" ");
+ col = 0;
+ return;
+ }
+ var escaped = "";
+ // HTML-escape and replace tabs
+ for (var pos = 0;;) {
+ var idx = text.indexOf("\t", pos);
+ if (idx == -1) {
+ escaped += CodeMirror.htmlEscape(text.slice(pos));
+ col += text.length - pos;
+ break;
+ } else {
+ col += idx - pos;
+ escaped += CodeMirror.htmlEscape(text.slice(pos, idx));
+ var size = tabSize - col % tabSize;
+ col += size;
+ for (var i = 0; i < size; ++i) escaped += " ";
+ pos = idx + 1;
+ }
+ }
+
+ if (style)
+ accum.push("" + escaped + "");
+ else
+ accum.push(escaped);
+ }
+ }
+ var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
+ for (var i = 0, e = lines.length; i < e; ++i) {
+ if (i) callback("\n");
+ var stream = new CodeMirror.StringStream(lines[i]);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state);
+ callback(stream.current(), style, i, stream.start);
+ stream.start = stream.pos;
+ }
+ }
+ if (isNode)
+ node.innerHTML = accum.join("");
+};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/search.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/search.js
new file mode 100644
index 0000000000..c5a2bccfaf
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/search.js
@@ -0,0 +1,118 @@
+// Define search commands. Depends on dialog.js or another
+// implementation of the openDialog method.
+
+// Replace works a little oddly -- it will do the replace on the next
+// Ctrl-G (or whatever is bound to findNext) press. You prevent a
+// replace by making sure the match is no longer selected when hitting
+// Ctrl-G.
+
+(function() {
+ function SearchState() {
+ this.posFrom = this.posTo = this.query = null;
+ this.marked = [];
+ }
+ function getSearchState(cm) {
+ return cm._searchState || (cm._searchState = new SearchState());
+ }
+ function getSearchCursor(cm, query, pos) {
+ // Heuristic: if the query string is all lowercase, do a case insensitive search.
+ return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
+ }
+ function dialog(cm, text, shortText, f) {
+ if (cm.openDialog) cm.openDialog(text, f);
+ else f(prompt(shortText, ""));
+ }
+ function confirmDialog(cm, text, shortText, fs) {
+ if (cm.openConfirm) cm.openConfirm(text, fs);
+ else if (confirm(shortText)) fs[0]();
+ }
+ function parseQuery(query) {
+ var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
+ return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
+ }
+ var queryDialog =
+ 'Search: (Use /re/ syntax for regexp search)';
+ function doSearch(cm, rev) {
+ var state = getSearchState(cm);
+ if (state.query) return findNext(cm, rev);
+ dialog(cm, queryDialog, "Search for:", function(query) {
+ cm.operation(function() {
+ if (!query || state.query) return;
+ state.query = parseQuery(query);
+ if (cm.lineCount() < 2000) { // This is too expensive on big documents.
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();)
+ state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching"));
+ }
+ state.posFrom = state.posTo = cm.getCursor();
+ findNext(cm, rev);
+ });
+ });
+ }
+ function findNext(cm, rev) {cm.operation(function() {
+ var state = getSearchState(cm);
+ var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
+ if (!cursor.find(rev)) {
+ cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
+ if (!cursor.find(rev)) return;
+ }
+ cm.setSelection(cursor.from(), cursor.to());
+ state.posFrom = cursor.from(); state.posTo = cursor.to();
+ })}
+ function clearSearch(cm) {cm.operation(function() {
+ var state = getSearchState(cm);
+ if (!state.query) return;
+ state.query = null;
+ for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
+ state.marked.length = 0;
+ })}
+
+ var replaceQueryDialog =
+ 'Replace: (Use /re/ syntax for regexp search)';
+ var replacementQueryDialog = 'With: ';
+ var doReplaceConfirm = "Replace? ";
+ function replace(cm, all) {
+ dialog(cm, replaceQueryDialog, "Replace:", function(query) {
+ if (!query) return;
+ query = parseQuery(query);
+ dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
+ if (all) {
+ cm.compoundChange(function() { cm.operation(function() {
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
+ if (typeof query != "string") {
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
+ cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];}));
+ } else cursor.replace(text);
+ }
+ })});
+ } else {
+ clearSearch(cm);
+ var cursor = getSearchCursor(cm, query, cm.getCursor());
+ function advance() {
+ var start = cursor.from(), match;
+ if (!(match = cursor.findNext())) {
+ cursor = getSearchCursor(cm, query);
+ if (!(match = cursor.findNext()) ||
+ (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
+ }
+ cm.setSelection(cursor.from(), cursor.to());
+ confirmDialog(cm, doReplaceConfirm, "Replace?",
+ [function() {doReplace(match);}, advance]);
+ }
+ function doReplace(match) {
+ cursor.replace(typeof query == "string" ? text :
+ text.replace(/\$(\d)/, function(w, i) {return match[i];}));
+ advance();
+ }
+ advance();
+ }
+ });
+ });
+ }
+
+ CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
+ CodeMirror.commands.findNext = doSearch;
+ CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
+ CodeMirror.commands.clearSearch = clearSearch;
+ CodeMirror.commands.replace = replace;
+ CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/searchcursor.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/searchcursor.js
new file mode 100644
index 0000000000..ec3f73c3fa
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/searchcursor.js
@@ -0,0 +1,117 @@
+(function(){
+ function SearchCursor(cm, query, pos, caseFold) {
+ this.atOccurrence = false; this.cm = cm;
+ if (caseFold == null && typeof query == "string") caseFold = false;
+
+ pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0};
+ this.pos = {from: pos, to: pos};
+
+ // The matches method is filled in based on the type of query.
+ // It takes a position and a direction, and returns an object
+ // describing the next occurrence of the query, or null if no
+ // more matches were found.
+ if (typeof query != "string") // Regexp match
+ this.matches = function(reverse, pos) {
+ if (reverse) {
+ var line = cm.getLine(pos.line).slice(0, pos.ch), match = line.match(query), start = 0;
+ while (match) {
+ var ind = line.indexOf(match[0]);
+ start += ind;
+ line = line.slice(ind + 1);
+ var newmatch = line.match(query);
+ if (newmatch) match = newmatch;
+ else break;
+ start++;
+ }
+ }
+ else {
+ var line = cm.getLine(pos.line).slice(pos.ch), match = line.match(query),
+ start = match && pos.ch + line.indexOf(match[0]);
+ }
+ if (match)
+ return {from: {line: pos.line, ch: start},
+ to: {line: pos.line, ch: start + match[0].length},
+ match: match};
+ };
+ else { // String query
+ if (caseFold) query = query.toLowerCase();
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
+ var target = query.split("\n");
+ // Different methods for single-line and multi-line queries
+ if (target.length == 1)
+ this.matches = function(reverse, pos) {
+ var line = fold(cm.getLine(pos.line)), len = query.length, match;
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
+ : (match = line.indexOf(query, pos.ch)) != -1)
+ return {from: {line: pos.line, ch: match},
+ to: {line: pos.line, ch: match + len}};
+ };
+ else
+ this.matches = function(reverse, pos) {
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
+ if (reverse ? offsetA >= pos.ch || offsetA != match.length
+ : offsetA <= pos.ch || offsetA != line.length - match.length)
+ return;
+ for (;;) {
+ if (reverse ? !ln : ln == cm.lineCount() - 1) return;
+ line = fold(cm.getLine(ln += reverse ? -1 : 1));
+ match = target[reverse ? --idx : ++idx];
+ if (idx > 0 && idx < target.length - 1) {
+ if (line != match) return;
+ else continue;
+ }
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
+ return;
+ var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
+ return {from: reverse ? end : start, to: reverse ? start : end};
+ }
+ };
+ }
+ }
+
+ SearchCursor.prototype = {
+ findNext: function() {return this.find(false);},
+ findPrevious: function() {return this.find(true);},
+
+ find: function(reverse) {
+ var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to);
+ function savePosAndFail(line) {
+ var pos = {line: line, ch: 0};
+ self.pos = {from: pos, to: pos};
+ self.atOccurrence = false;
+ return false;
+ }
+
+ for (;;) {
+ if (this.pos = this.matches(reverse, pos)) {
+ this.atOccurrence = true;
+ return this.pos.match || true;
+ }
+ if (reverse) {
+ if (!pos.line) return savePosAndFail(0);
+ pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length};
+ }
+ else {
+ var maxLine = this.cm.lineCount();
+ if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
+ pos = {line: pos.line+1, ch: 0};
+ }
+ }
+ },
+
+ from: function() {if (this.atOccurrence) return this.pos.from;},
+ to: function() {if (this.atOccurrence) return this.pos.to;},
+
+ replace: function(newText) {
+ var self = this;
+ if (this.atOccurrence)
+ self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to);
+ }
+ };
+
+ CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
+ return new SearchCursor(this, query, pos, caseFold);
+ });
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.css b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.css
new file mode 100644
index 0000000000..4387cb9411
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.css
@@ -0,0 +1,16 @@
+.CodeMirror-completions {
+ position: absolute;
+ z-index: 10;
+ overflow: hidden;
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+}
+.CodeMirror-completions select {
+ background: #fafafa;
+ outline: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ font-family: monospace;
+}
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.js
new file mode 100644
index 0000000000..f6bfd983b2
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/simple-hint.js
@@ -0,0 +1,86 @@
+(function () {
+ CodeMirror.simpleHint = function (editor, getHints) {
+ // We want a single cursor position.
+ if (editor.somethingSelected()) return;
+ //don't show completion if the token is empty
+ var tempToken = editor.getTokenAt(editor.getCursor());
+ if (!(/[\S]/gi.test(tempToken.string))) return;
+
+ var result = getHints(editor);
+ if (!result || !result.list.length) return;
+ var completions = result.list;
+ function insert(str) {
+ editor.replaceRange(str, result.from, result.to);
+ }
+ // When there is only one completion, use it directly.
+ if (completions.length == 1) { insert(completions[0]); return true; }
+
+ // Build the select widget
+ var complete = document.createElement("div");
+ complete.className = "CodeMirror-completions";
+ var sel = complete.appendChild(document.createElement("select"));
+ // Opera doesn't move the selection when pressing up/down in a
+ // multi-select, but it does properly support the size property on
+ // single-selects, so no multi-select is necessary.
+ if (!window.opera) sel.multiple = true;
+
+ for (var i = 0; i < completions.length; ++i) {
+ var opt = sel.appendChild(document.createElement("option"));
+ var completion = completions[i];
+
+ if (typeof completion === 'string') {
+ opt.appendChild(document.createTextNode(completion));
+ opt.setAttribute("value", completion);
+ }
+ else {
+ opt.appendChild(document.createTextNode(completion[0]));
+ opt.setAttribute("value", completion[1]);
+ }
+ }
+ sel.firstChild.selected = true;
+ sel.size = Math.min(10, completions.length);
+ var pos = editor.cursorCoords();
+ complete.style.left = pos.x + "px";
+ complete.style.top = pos.yBot + "px";
+ document.body.appendChild(complete);
+ // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
+ var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
+ if (winW - pos.x < sel.clientWidth)
+ complete.style.left = (pos.x - sel.clientWidth) + "px";
+ // Hack to hide the scrollbar.
+ if (completions.length <= 10)
+ complete.style.width = (sel.clientWidth - 1) + "px";
+
+ var done = false;
+ function close() {
+ if (done) return;
+ done = true;
+ complete.parentNode.removeChild(complete);
+ }
+ function pick() {
+ insert(completions[sel.selectedIndex][1]);
+ close();
+ setTimeout(function () { editor.focus(); }, 50);
+ }
+ CodeMirror.connect(sel, "blur", close);
+ CodeMirror.connect(sel, "keydown", function (event) {
+ var code = event.keyCode;
+ // Enter
+ if (code == 13) { CodeMirror.e_stop(event); pick(); }
+ // Escape
+ else if (code == 27) { CodeMirror.e_stop(event); close(); editor.focus(); }
+ else if (code != 38 && code != 40) {
+ close(); editor.focus();
+ // Pass the event to the CodeMirror instance so that it can handle things like backspace properly.
+ editor.triggerOnKeyDown(event);
+ setTimeout(function () { CodeMirror.simpleHint(editor, getHints); }, 50);
+ }
+ });
+ CodeMirror.connect(sel, "dblclick", pick);
+
+ sel.focus();
+ // Opera sometimes ignores focusing a freshly created node
+ if (window.opera) setTimeout(function () { if (!done) sel.focus(); }, 100);
+ return true;
+ };
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/xml-hint.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/xml-hint.js
new file mode 100644
index 0000000000..5f04976c7b
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/lib/util/xml-hint.js
@@ -0,0 +1,135 @@
+
+(function() {
+
+ CodeMirror.xmlHints = [];
+ CodeMirror.xmlHint = function(cm, simbol) {
+ if(simbol.length > 0) {
+ var cursor = cm.getCursor();
+ cm.replaceSelection(simbol);
+ cursor = {line: cursor.line, ch: cursor.ch + 1};
+ cm.setCursor(cursor);
+ }
+
+ // dirty hack for simple-hint to receive getHint event on space
+ var getTokenAt = editor.getTokenAt;
+
+ editor.getTokenAt = function() { return 'disabled'; }
+ CodeMirror.simpleHint(cm, getHint);
+
+ editor.getTokenAt = getTokenAt;
+ };
+
+ var getHint = function(cm) {
+
+ var cursor = cm.getCursor();
+
+ if (cursor.ch > 0) {
+
+ var text = cm.getRange({line: 0, ch: 0}, cursor);
+ var typed = '';
+ var simbol = '';
+ for(var i = text.length - 1; i >= 0; i--) {
+ if(text[i] == ' ' || text[i] == '<') {
+ simbol = text[i];
+ break;
+ }
+ else {
+ typed = text[i] + typed;
+ }
+ }
+
+ text = text.substr(0, text.length - typed.length);
+
+ var path = getActiveElement(cm, text) + simbol;
+ var hints = CodeMirror.xmlHints[path];
+
+ if(typeof hints === 'undefined')
+ hints = [''];
+ else {
+ hints = hints.slice(0);
+ for (var i = hints.length - 1; i >= 0; i--) {
+ if(hints[i].indexOf(typed) != 0)
+ hints.splice(i, 1);
+ }
+ }
+
+ return {
+ list: hints,
+ from: { line: cursor.line, ch: cursor.ch - typed.length },
+ to: cursor,
+ };
+ };
+ }
+
+ var getActiveElement = function(codeMirror, text) {
+
+ var element = '';
+
+ if(text.length >= 0) {
+
+ var regex = new RegExp('<([^!?][^\\s/>]*).*?>', 'g');
+
+ var matches = [];
+ var match;
+ while ((match = regex.exec(text)) != null) {
+ matches.push({
+ tag: match[1],
+ selfclose: (match[0].substr(-1) === '/>')
+ });
+ }
+
+ for (var i = matches.length - 1, skip = 0; i >= 0; i--) {
+
+ var item = matches[i];
+
+ if (item.tag[0] == '/')
+ {
+ skip++;
+ }
+ else if (item.selfclose == false)
+ {
+ if (skip > 0)
+ {
+ skip--;
+ }
+ else
+ {
+ element = '<' + item.tag + '>' + element;
+ }
+ }
+ }
+
+ element += getOpenTag(text);
+ }
+
+ return element;
+ };
+
+ var getOpenTag = function(text) {
+
+ var open = text.lastIndexOf('<');
+ var close = text.lastIndexOf('>');
+
+ if (close < open)
+ {
+ text = text.substr(open);
+
+ if(text != '<') {
+
+ var space = text.indexOf(' ');
+ if(space < 0)
+ space = text.indexOf('\t');
+ if(space < 0)
+ space = text.indexOf('\n');
+
+ if (space < 0)
+ space = text.length;
+
+ return text.substr(0, space);
+ }
+ }
+
+ return '';
+ };
+
+})();
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mirrorframe.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mirrorframe.js
deleted file mode 100644
index bd0ec76112..0000000000
--- a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mirrorframe.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* Demonstration of embedding CodeMirror in a bigger application. The
- * interface defined here is a mess of prompts and confirms, and
- * should probably not be used in a real project.
- */
-
-function MirrorFrame(place, options) {
- this.home = document.createElement("div");
- if (place.appendChild)
- place.appendChild(this.home);
- else
- place(this.home);
-
- var self = this;
- function makeButton(name, action) {
- var button = document.createElement("input");
- button.type = "button";
- button.value = name;
- self.home.appendChild(button);
- button.onclick = function(){self[action].call(self);};
- }
-
- makeButton("Search", "search");
- makeButton("Replace", "replace");
- makeButton("Current line", "line");
- makeButton("Jump to line", "jump");
- makeButton("Insert constructor", "macro");
- makeButton("Indent all", "reindent");
-
- this.mirror = new CodeMirror(this.home, options);
-}
-
-MirrorFrame.prototype = {
- search: function() {
- var text = prompt("Enter search term:", "");
- if (!text) return;
-
- var first = true;
- do {
- var cursor = this.mirror.getSearchCursor(text, first);
- first = false;
- while (cursor.findNext()) {
- cursor.select();
- if (!confirm("Search again?"))
- return;
- }
- } while (confirm("End of document reached. Start over?"));
- },
-
- replace: function() {
- // This is a replace-all, but it is possible to implement a
- // prompting replace.
- var from = prompt("Enter search string:", ""), to;
- if (from) to = prompt("What should it be replaced with?", "");
- if (to == null) return;
-
- var cursor = this.mirror.getSearchCursor(from, false);
- while (cursor.findNext())
- cursor.replace(to);
- },
-
- jump: function() {
- var line = prompt("Jump to line:", "");
- if (line && !isNaN(Number(line)))
- this.mirror.jumpToLine(Number(line));
- },
-
- line: function() {
- alert("The cursor is currently at line " + this.mirror.currentLine());
- this.mirror.focus();
- },
-
- macro: function() {
- var name = prompt("Name your constructor:", "");
- if (name)
- this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n");
- },
-
- reindent: function() {
- this.mirror.reindent();
- }
-};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/clike.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/clike.js
new file mode 100644
index 0000000000..e0c7d18e55
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/clike.js
@@ -0,0 +1,280 @@
+CodeMirror.defineMode("clike", function(config, parserConfig) {
+ var indentUnit = config.indentUnit,
+ keywords = parserConfig.keywords || {},
+ builtin = parserConfig.builtin || {},
+ blockKeywords = parserConfig.blockKeywords || {},
+ atoms = parserConfig.atoms || {},
+ hooks = parserConfig.hooks || {},
+ multiLineStrings = parserConfig.multiLineStrings;
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+ var curPunc;
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (hooks[ch]) {
+ var result = hooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ curPunc = ch;
+ return null;
+ }
+ if (/\d/.test(ch)) {
+ stream.eatWhile(/[\w\.]/);
+ return "number";
+ }
+ if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ }
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return "operator";
+ }
+ stream.eatWhile(/[\w\$_]/);
+ var cur = stream.current();
+ if (keywords.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "keyword";
+ }
+ if (builtin.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "builtin";
+ }
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
+ return "variable";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {end = true; break;}
+ escaped = !escaped && next == "\\";
+ }
+ if (end || !(escaped || multiLineStrings))
+ state.tokenize = null;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ function Context(indented, column, type, align, prev) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.align = align;
+ this.prev = prev;
+ }
+ function pushContext(state, col, type) {
+ return state.context = new Context(state.indented, col, type, null, state.context);
+ }
+ function popContext(state) {
+ var t = state.context.type;
+ if (t == ")" || t == "]" || t == "}")
+ state.indented = state.context.indented;
+ return state.context = state.context.prev;
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {
+ tokenize: null,
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+ indented: 0,
+ startOfLine: true
+ };
+ },
+
+ token: function(stream, state) {
+ var ctx = state.context;
+ if (stream.sol()) {
+ if (ctx.align == null) ctx.align = false;
+ state.indented = stream.indentation();
+ state.startOfLine = true;
+ }
+ if (stream.eatSpace()) return null;
+ curPunc = null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style == "comment" || style == "meta") return style;
+ if (ctx.align == null) ctx.align = true;
+
+ if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
+ else if (curPunc == "}") {
+ while (ctx.type == "statement") ctx = popContext(state);
+ if (ctx.type == "}") ctx = popContext(state);
+ while (ctx.type == "statement") ctx = popContext(state);
+ }
+ else if (curPunc == ctx.type) popContext(state);
+ else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+ pushContext(state, stream.column(), "statement");
+ state.startOfLine = false;
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+ if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+ var closing = firstChar == ctx.type;
+ if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+ else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+ else return ctx.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricChars: "{}"
+ };
+});
+
+(function() {
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+ var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
+ "double static else struct entry switch extern typedef float union for unsigned " +
+ "goto while enum void const signed volatile";
+
+ function cppHook(stream, state) {
+ if (!state.startOfLine) return false;
+ stream.skipToEnd();
+ return "meta";
+ }
+
+ // C#-style strings where "" escapes a quote.
+ function tokenAtString(stream, state) {
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next == '"' && !stream.eat('"')) {
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "string";
+ }
+
+ CodeMirror.defineMIME("text/x-csrc", {
+ name: "clike",
+ keywords: words(cKeywords),
+ blockKeywords: words("case do else for if switch while struct"),
+ atoms: words("null"),
+ hooks: {"#": cppHook}
+ });
+ CodeMirror.defineMIME("text/x-c++src", {
+ name: "clike",
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
+ "static_cast typeid catch operator template typename class friend private " +
+ "this using const_cast inline public throw virtual delete mutable protected " +
+ "wchar_t"),
+ blockKeywords: words("catch class do else finally for if struct switch try while"),
+ atoms: words("true false null"),
+ hooks: {"#": cppHook}
+ });
+ CodeMirror.defineMIME("text/x-java", {
+ name: "clike",
+ keywords: words("abstract assert boolean break byte case catch char class const continue default " +
+ "do double else enum extends final finally float for goto if implements import " +
+ "instanceof int interface long native new package private protected public " +
+ "return short static strictfp super switch synchronized this throw throws transient " +
+ "try void volatile while"),
+ blockKeywords: words("catch class do else finally for if switch try while"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+ CodeMirror.defineMIME("text/x-csharp", {
+ name: "clike",
+ keywords: words("abstract as base break case catch checked class const continue" +
+ " default delegate do else enum event explicit extern finally fixed for" +
+ " foreach goto if implicit in interface internal is lock namespace new" +
+ " operator out override params private protected public readonly ref return sealed" +
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+ " global group into join let orderby partial remove select set value var yield"),
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+ builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+ " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
+ " UInt64 bool byte char decimal double short int long object" +
+ " sbyte float string ushort uint ulong"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ if (stream.eat('"')) {
+ state.tokenize = tokenAtString;
+ return tokenAtString(stream, state);
+ }
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+ CodeMirror.defineMIME("text/x-scala", {
+ name: "clike",
+ keywords: words(
+
+ /* scala */
+ "abstract case catch class def do else extends false final finally for forSome if " +
+ "implicit import lazy match new null object override package private protected return " +
+ "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
+ "<% >: # @ " +
+
+ /* package scala */
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
+ "readChar readInt readLong readFloat readDouble " +
+
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
+
+ /* package java.lang */
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
+
+
+ ),
+ blockKeywords: words("catch class do else finally for forSome if match switch try while"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+}());
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/index.html
new file mode 100644
index 0000000000..64d02f11e7
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/clike/index.html
@@ -0,0 +1,101 @@
+
+
+
+ CodeMirror: C-like mode
+
+
+
+
+
+
+
+
CodeMirror: C-like mode
+
+
+
+
+
+
Simple mode that tries to handle C-like languages as well as it
+ can. Takes two configuration parameters: keywords, an
+ object whose property names are the keywords in the language,
+ and useCPP, which determines whether C preprocessor
+ directives are recognized.
Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
+ JavaScript, CSS and XML. Other dependancies include those of the scriping language chosen.
MIME types defined:text/x-less, text/css (if not previously defined).
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/less/less.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/less/less.js
new file mode 100644
index 0000000000..e80beb149e
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/less/less.js
@@ -0,0 +1,232 @@
+/*
+ LESS mode - http://www.lesscss.org/
+ Ported to CodeMirror by Peter Kroon
+*/
+
+CodeMirror.defineMode("less", function(config) {
+ var indentUnit = config.indentUnit, type;
+ function ret(style, tp) {type = tp; return style;}
+ //html5 tags
+ var tags = ["a","abbr","acronym","address","applet","area","article","aside","audio","b","base","basefont","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","command","datalist","dd","del","details","dfn","dir","div","dl","dt","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","keygen","kbd","label","legend","li","link","map","mark","menu","meta","meter","nav","noframes","noscript","object","ol","optgroup","option","output","p","param","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strike","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr"];
+
+ function inTagsArray(val){
+ for(var i=0; i*\/]/.test(ch)) {//removed . dot character original was [,.+>*\/]
+ return ret(null, "select-op");
+ }
+ else if (/[;{}:\[\]()]/.test(ch)) { //added () char for lesscss original was [;{}:\[\]]
+ if(ch == ":"){
+ stream.eatWhile(/[active|hover|link|visited]/);
+ if( stream.current().match(/active|hover|link|visited/)){
+ return ret("tag", "tag");
+ }else{
+ return ret(null, ch);
+ }
+ }else{
+ return ret(null, ch);
+ }
+ }
+ else if (ch == ".") { // lesscss
+ stream.eatWhile(/[\a-zA-Z0-9\-_]/);
+ return ret("tag", "tag");
+ }
+ else if (ch == "#") { // lesscss
+ //we don't eat white-space, we want the hex color and or id only
+ stream.eatWhile(/[A-Za-z0-9]/);
+ //check if there is a proper hex color length e.g. #eee || #eeeEEE
+ if(stream.current().length ===4 || stream.current().length ===7){
+ if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
+ //when not a valid hex value, parse as id
+ if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
+ //eat white-space
+ stream.eatSpace();
+ //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
+ if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
+ //#time { color: #aaa }
+ else if(stream.peek() == "}" )return ret("number", "unit");
+ //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
+ else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
+ //when a hex value is on the end of a line, parse as id
+ else if(stream.eol())return ret("atom", "tag");
+ //default
+ else return ret("number", "unit");
+ }else{//when not a valid hexvalue in the current stream e.g. #footer
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("atom", "tag");
+ }
+ }else{
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("atom", "tag");
+ }
+ }
+ else if (ch == "&") {
+ stream.eatWhile(/[\w\-]/);
+ return ret(null, ch);
+ }
+ else {
+ stream.eatWhile(/[\w\\\-_%.{]/);
+ if(stream.current().match(/http|https/) != null){
+ stream.eatWhile(/[\w\\\-_%.{:\/]/);
+ return ret("string", "string");
+ }else if(stream.peek() == "<" || stream.peek() == ">"){
+ return ret("tag", "tag");
+ }else if( stream.peek().match(/\(/) != null ){// lessc
+ return ret(null, ch);
+ }else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
+ return ret("string", "string");
+ }else if( stream.current().match(/\-\d|\-.\d/) ){ // lesscss match e.g.: -5px -0.4 etc... only colorize the minus sign
+ //stream.backUp(stream.current().length-1); //commment out these 2 comment if you want the minus sign to be parsed as null -500px
+ //return ret(null, ch);
+ return ret("number", "unit");
+ }else if( inTagsArray(stream.current()) ){ // lesscss match html tags
+ return ret("tag", "tag");
+ }else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
+ if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
+ stream.backUp(1);
+ return ret("tag", "tag");
+ }//end if
+ if( (stream.eatSpace() && stream.peek().match(/[{<>.a-zA-Z]/) != null) || stream.eol() )return ret("tag", "tag");//e.g. button.icon-plus
+ return ret("string", "string");//let url(/images/logo.png) without quotes return as string
+ }else if( stream.eol() ){
+ if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
+ return ret("tag", "tag");
+ }else{
+ return ret("variable", "variable");
+ }
+ }
+
+ }
+
+ function tokenSComment(stream, state) {// SComment = Slash comment
+ stream.skipToEnd();
+ state.tokenize = tokenBase;
+ return ret("comment", "comment");
+ }
+
+ function tokenCComment(stream, state) {
+ var maybeEnd = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (maybeEnd && ch == "/") {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenSGMLComment(stream, state) {
+ var dashes = 0, ch;
+ while ((ch = stream.next()) != null) {
+ if (dashes >= 2 && ch == ">") {
+ state.tokenize = tokenBase;
+ break;
+ }
+ dashes = (ch == "-") ? dashes + 1 : 0;
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == quote && !escaped)
+ break;
+ escaped = !escaped && ch == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ return {
+ startState: function(base) {
+ return {tokenize: tokenBase,
+ baseIndent: base || 0,
+ stack: []};
+ },
+
+ token: function(stream, state) {
+ if (stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+
+ var context = state.stack[state.stack.length-1];
+ if (type == "hash" && context == "rule") style = "atom";
+ else if (style == "variable") {
+ if (context == "rule") style = null; //"tag"
+ else if (!context || context == "@media{"){
+ style = stream.current() == "when" ? "variable" :
+ stream.string.match(/#/g) != undefined ? null :
+ /[\s,|\s\)]/.test(stream.peek()) ? "tag" : null;
+ }
+ }
+
+ if (context == "rule" && /^[\{\};]$/.test(type))
+ state.stack.pop();
+ if (type == "{") {
+ if (context == "@media") state.stack[state.stack.length-1] = "@media{";
+ else state.stack.push("{");
+ }
+ else if (type == "}") state.stack.pop();
+ else if (type == "@media") state.stack.push("@media");
+ else if (context == "{" && type != "comment") state.stack.push("rule");
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ var n = state.stack.length;
+ if (/^\}/.test(textAfter))
+ n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
+ return state.baseIndent + n * indentUnit;
+ },
+
+ electricChars: "}"
+ };
+});
+
+CodeMirror.defineMIME("text/x-less", "less");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
+ CodeMirror.defineMIME("text/css", "less");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/lua/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/lua/index.html
new file mode 100644
index 0000000000..600ddb0e41
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/lua/index.html
@@ -0,0 +1,72 @@
+
+
+
+ CodeMirror: Lua mode
+
+
+
+
+
+
+
+
+
CodeMirror: Lua mode
+
+
+
+
Loosely based on Franciszek
+ Wawrzak's CodeMirror
+ 1 mode. One configuration parameter is
+ supported, specials, to which you can provide an
+ array of strings to have those identifiers highlighted with
+ the lua-special style.
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ocaml/ocaml.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ocaml/ocaml.js
new file mode 100644
index 0000000000..294d9446ad
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ocaml/ocaml.js
@@ -0,0 +1,114 @@
+CodeMirror.defineMode('ocaml', function(config) {
+
+ var words = {
+ 'true': 'atom',
+ 'false': 'atom',
+ 'let': 'keyword',
+ 'rec': 'keyword',
+ 'in': 'keyword',
+ 'of': 'keyword',
+ 'and': 'keyword',
+ 'succ': 'keyword',
+ 'if': 'keyword',
+ 'then': 'keyword',
+ 'else': 'keyword',
+ 'for': 'keyword',
+ 'to': 'keyword',
+ 'while': 'keyword',
+ 'do': 'keyword',
+ 'done': 'keyword',
+ 'fun': 'keyword',
+ 'function': 'keyword',
+ 'val': 'keyword',
+ 'type': 'keyword',
+ 'mutable': 'keyword',
+ 'match': 'keyword',
+ 'with': 'keyword',
+ 'try': 'keyword',
+ 'raise': 'keyword',
+ 'begin': 'keyword',
+ 'end': 'keyword',
+ 'open': 'builtin',
+ 'trace': 'builtin',
+ 'ignore': 'builtin',
+ 'exit': 'builtin',
+ 'print_string': 'builtin',
+ 'print_endline': 'builtin'
+ };
+
+ function tokenBase(stream, state) {
+ var sol = stream.sol();
+ var ch = stream.next();
+
+ if (ch === '"') {
+ state.tokenize = tokenString;
+ return state.tokenize(stream, state);
+ }
+ if (ch === '(') {
+ if (stream.eat('*')) {
+ state.commentLevel++;
+ state.tokenize = tokenComment;
+ return state.tokenize(stream, state);
+ }
+ }
+ if (ch === '~') {
+ stream.eatWhile(/\w/);
+ return 'variable-2';
+ }
+ if (ch === '`') {
+ stream.eatWhile(/\w/);
+ return 'quote';
+ }
+ if (/\d/.test(ch)) {
+ stream.eatWhile(/[\d]/);
+ if (stream.eat('.')) {
+ stream.eatWhile(/[\d]/);
+ }
+ return 'number';
+ }
+ if ( /[+\-*&%=<>!?|]/.test(ch)) {
+ return 'operator';
+ }
+ stream.eatWhile(/\w/);
+ var cur = stream.current();
+ return words[cur] || 'variable';
+ }
+
+ function tokenString(stream, state) {
+ var next, end = false, escaped = false;
+ while ((next = stream.next()) != null) {
+ if (next === '"' && !escaped) {
+ end = true;
+ break;
+ }
+ escaped = !escaped && next === '\\';
+ }
+ if (end && !escaped) {
+ state.tokenize = tokenBase;
+ }
+ return 'string';
+ };
+
+ function tokenComment(stream, state) {
+ var prev, next;
+ while(state.commentLevel > 0 && (next = stream.next()) != null) {
+ if (prev === '(' && next === '*') state.commentLevel++;
+ if (prev === '*' && next === ')') state.commentLevel--;
+ prev = next;
+ }
+ if (state.commentLevel <= 0) {
+ state.tokenize = tokenBase;
+ }
+ return 'comment';
+ }
+
+ return {
+ startState: function() {return {tokenize: tokenBase, commentLevel: 0}},
+ token: function(stream, state) {
+ if (stream.eatSpace()) return null;
+ return state.tokenize(stream, state);
+ }
+ };
+});
+
+CodeMirror.defineMIME('text/x-ocaml', 'ocaml');
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/LICENSE b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/LICENSE
new file mode 100644
index 0000000000..8e3747e748
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/LICENSE
@@ -0,0 +1,7 @@
+Copyright (c) 2011 souceLair
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/index.html
new file mode 100644
index 0000000000..6af6b460e2
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/index.html
@@ -0,0 +1,48 @@
+
+
+
+ CodeMirror: Pascal mode
+
+
+
+
+
+
+
+
CodeMirror: Pascal mode
+
+
+
+
+
+
MIME types defined:text/x-pascal.
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/pascal.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/pascal.js
new file mode 100644
index 0000000000..55d1fb65de
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/pascal/pascal.js
@@ -0,0 +1,94 @@
+CodeMirror.defineMode("pascal", function(config) {
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+ var keywords = words("and array begin case const div do downto else end file for forward integer " +
+ "boolean char function goto if in label mod nil not of or packed procedure " +
+ "program record repeat set string then to type until var while with");
+ var atoms = {"null": true};
+
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == "#" && state.startOfLine) {
+ stream.skipToEnd();
+ return "meta";
+ }
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (ch == "(" && stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ }
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return null
+ }
+ if (/\d/.test(ch)) {
+ stream.eatWhile(/[\w\.]/);
+ return "number";
+ }
+ if (ch == "/") {
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return "operator";
+ }
+ stream.eatWhile(/[\w\$_]/);
+ var cur = stream.current();
+ if (keywords.propertyIsEnumerable(cur)) return "keyword";
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
+ return "variable";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {end = true; break;}
+ escaped = !escaped && next == "\\";
+ }
+ if (end || !escaped) state.tokenize = null;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == ")" && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {tokenize: null};
+ },
+
+ token: function(stream, state) {
+ if (stream.eatSpace()) return null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style == "comment" || style == "meta") return style;
+ return style;
+ },
+
+ electricChars: "{}"
+ };
+});
+
+CodeMirror.defineMIME("text/x-pascal", "pascal");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/LICENSE b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/LICENSE
new file mode 100644
index 0000000000..96f4115af8
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/LICENSE
@@ -0,0 +1,19 @@
+Copyright (C) 2011 by Sabaca under the MIT license.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/index.html
new file mode 100644
index 0000000000..5ef55d323d
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/index.html
@@ -0,0 +1,62 @@
+
+
+
+ CodeMirror: Perl mode
+
+
+
+
+
+
+
+
CodeMirror: Perl mode
+
+
+
+
+
+
MIME types defined:text/x-perl.
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/perl.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/perl.js
new file mode 100644
index 0000000000..7fa129eac6
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/perl/perl.js
@@ -0,0 +1,816 @@
+// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
+// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)
+CodeMirror.defineMode("perl",function(config,parserConfig){
+ // http://perldoc.perl.org
+ var PERL={ // null - magic touch
+ // 1 - keyword
+ // 2 - def
+ // 3 - atom
+ // 4 - operator
+ // 5 - variable-2 (predefined)
+ // [x,y] - x=1,2,3; y=must be defined if x{...}
+ // PERL operators
+ '->' : 4,
+ '++' : 4,
+ '--' : 4,
+ '**' : 4,
+ // ! ~ \ and unary + and -
+ '=~' : 4,
+ '!~' : 4,
+ '*' : 4,
+ '/' : 4,
+ '%' : 4,
+ 'x' : 4,
+ '+' : 4,
+ '-' : 4,
+ '.' : 4,
+ '<<' : 4,
+ '>>' : 4,
+ // named unary operators
+ '<' : 4,
+ '>' : 4,
+ '<=' : 4,
+ '>=' : 4,
+ 'lt' : 4,
+ 'gt' : 4,
+ 'le' : 4,
+ 'ge' : 4,
+ '==' : 4,
+ '!=' : 4,
+ '<=>' : 4,
+ 'eq' : 4,
+ 'ne' : 4,
+ 'cmp' : 4,
+ '~~' : 4,
+ '&' : 4,
+ '|' : 4,
+ '^' : 4,
+ '&&' : 4,
+ '||' : 4,
+ '//' : 4,
+ '..' : 4,
+ '...' : 4,
+ '?' : 4,
+ ':' : 4,
+ '=' : 4,
+ '+=' : 4,
+ '-=' : 4,
+ '*=' : 4, // etc. ???
+ ',' : 4,
+ '=>' : 4,
+ '::' : 4,
+ // list operators (rightward)
+ 'not' : 4,
+ 'and' : 4,
+ 'or' : 4,
+ 'xor' : 4,
+ // PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
+ 'BEGIN' : [5,1],
+ 'END' : [5,1],
+ 'PRINT' : [5,1],
+ 'PRINTF' : [5,1],
+ 'GETC' : [5,1],
+ 'READ' : [5,1],
+ 'READLINE' : [5,1],
+ 'DESTROY' : [5,1],
+ 'TIE' : [5,1],
+ 'TIEHANDLE' : [5,1],
+ 'UNTIE' : [5,1],
+ 'STDIN' : 5,
+ 'STDIN_TOP' : 5,
+ 'STDOUT' : 5,
+ 'STDOUT_TOP' : 5,
+ 'STDERR' : 5,
+ 'STDERR_TOP' : 5,
+ '$ARG' : 5,
+ '$_' : 5,
+ '@ARG' : 5,
+ '@_' : 5,
+ '$LIST_SEPARATOR' : 5,
+ '$"' : 5,
+ '$PROCESS_ID' : 5,
+ '$PID' : 5,
+ '$$' : 5,
+ '$REAL_GROUP_ID' : 5,
+ '$GID' : 5,
+ '$(' : 5,
+ '$EFFECTIVE_GROUP_ID' : 5,
+ '$EGID' : 5,
+ '$)' : 5,
+ '$PROGRAM_NAME' : 5,
+ '$0' : 5,
+ '$SUBSCRIPT_SEPARATOR' : 5,
+ '$SUBSEP' : 5,
+ '$;' : 5,
+ '$REAL_USER_ID' : 5,
+ '$UID' : 5,
+ '$<' : 5,
+ '$EFFECTIVE_USER_ID' : 5,
+ '$EUID' : 5,
+ '$>' : 5,
+ '$a' : 5,
+ '$b' : 5,
+ '$COMPILING' : 5,
+ '$^C' : 5,
+ '$DEBUGGING' : 5,
+ '$^D' : 5,
+ '${^ENCODING}' : 5,
+ '$ENV' : 5,
+ '%ENV' : 5,
+ '$SYSTEM_FD_MAX' : 5,
+ '$^F' : 5,
+ '@F' : 5,
+ '${^GLOBAL_PHASE}' : 5,
+ '$^H' : 5,
+ '%^H' : 5,
+ '@INC' : 5,
+ '%INC' : 5,
+ '$INPLACE_EDIT' : 5,
+ '$^I' : 5,
+ '$^M' : 5,
+ '$OSNAME' : 5,
+ '$^O' : 5,
+ '${^OPEN}' : 5,
+ '$PERLDB' : 5,
+ '$^P' : 5,
+ '$SIG' : 5,
+ '%SIG' : 5,
+ '$BASETIME' : 5,
+ '$^T' : 5,
+ '${^TAINT}' : 5,
+ '${^UNICODE}' : 5,
+ '${^UTF8CACHE}' : 5,
+ '${^UTF8LOCALE}' : 5,
+ '$PERL_VERSION' : 5,
+ '$^V' : 5,
+ '${^WIN32_SLOPPY_STAT}' : 5,
+ '$EXECUTABLE_NAME' : 5,
+ '$^X' : 5,
+ '$1' : 5, // - regexp $1, $2...
+ '$MATCH' : 5,
+ '$&' : 5,
+ '${^MATCH}' : 5,
+ '$PREMATCH' : 5,
+ '$`' : 5,
+ '${^PREMATCH}' : 5,
+ '$POSTMATCH' : 5,
+ "$'" : 5,
+ '${^POSTMATCH}' : 5,
+ '$LAST_PAREN_MATCH' : 5,
+ '$+' : 5,
+ '$LAST_SUBMATCH_RESULT' : 5,
+ '$^N' : 5,
+ '@LAST_MATCH_END' : 5,
+ '@+' : 5,
+ '%LAST_PAREN_MATCH' : 5,
+ '%+' : 5,
+ '@LAST_MATCH_START' : 5,
+ '@-' : 5,
+ '%LAST_MATCH_START' : 5,
+ '%-' : 5,
+ '$LAST_REGEXP_CODE_RESULT' : 5,
+ '$^R' : 5,
+ '${^RE_DEBUG_FLAGS}' : 5,
+ '${^RE_TRIE_MAXBUF}' : 5,
+ '$ARGV' : 5,
+ '@ARGV' : 5,
+ 'ARGV' : 5,
+ 'ARGVOUT' : 5,
+ '$OUTPUT_FIELD_SEPARATOR' : 5,
+ '$OFS' : 5,
+ '$,' : 5,
+ '$INPUT_LINE_NUMBER' : 5,
+ '$NR' : 5,
+ '$.' : 5,
+ '$INPUT_RECORD_SEPARATOR' : 5,
+ '$RS' : 5,
+ '$/' : 5,
+ '$OUTPUT_RECORD_SEPARATOR' : 5,
+ '$ORS' : 5,
+ '$\\' : 5,
+ '$OUTPUT_AUTOFLUSH' : 5,
+ '$|' : 5,
+ '$ACCUMULATOR' : 5,
+ '$^A' : 5,
+ '$FORMAT_FORMFEED' : 5,
+ '$^L' : 5,
+ '$FORMAT_PAGE_NUMBER' : 5,
+ '$%' : 5,
+ '$FORMAT_LINES_LEFT' : 5,
+ '$-' : 5,
+ '$FORMAT_LINE_BREAK_CHARACTERS' : 5,
+ '$:' : 5,
+ '$FORMAT_LINES_PER_PAGE' : 5,
+ '$=' : 5,
+ '$FORMAT_TOP_NAME' : 5,
+ '$^' : 5,
+ '$FORMAT_NAME' : 5,
+ '$~' : 5,
+ '${^CHILD_ERROR_NATIVE}' : 5,
+ '$EXTENDED_OS_ERROR' : 5,
+ '$^E' : 5,
+ '$EXCEPTIONS_BEING_CAUGHT' : 5,
+ '$^S' : 5,
+ '$WARNING' : 5,
+ '$^W' : 5,
+ '${^WARNING_BITS}' : 5,
+ '$OS_ERROR' : 5,
+ '$ERRNO' : 5,
+ '$!' : 5,
+ '%OS_ERROR' : 5,
+ '%ERRNO' : 5,
+ '%!' : 5,
+ '$CHILD_ERROR' : 5,
+ '$?' : 5,
+ '$EVAL_ERROR' : 5,
+ '$@' : 5,
+ '$OFMT' : 5,
+ '$#' : 5,
+ '$*' : 5,
+ '$ARRAY_BASE' : 5,
+ '$[' : 5,
+ '$OLD_PERL_VERSION' : 5,
+ '$]' : 5,
+ // PERL blocks
+ 'if' :[1,1],
+ elsif :[1,1],
+ 'else' :[1,1],
+ 'while' :[1,1],
+ unless :[1,1],
+ 'for' :[1,1],
+ foreach :[1,1],
+ // PERL functions
+ 'abs' :1, // - absolute value function
+ accept :1, // - accept an incoming socket connect
+ alarm :1, // - schedule a SIGALRM
+ 'atan2' :1, // - arctangent of Y/X in the range -PI to PI
+ bind :1, // - binds an address to a socket
+ binmode :1, // - prepare binary files for I/O
+ bless :1, // - create an object
+ bootstrap :1, //
+ 'break' :1, // - break out of a "given" block
+ caller :1, // - get context of the current subroutine call
+ chdir :1, // - change your current working directory
+ chmod :1, // - changes the permissions on a list of files
+ chomp :1, // - remove a trailing record separator from a string
+ chop :1, // - remove the last character from a string
+ chown :1, // - change the owership on a list of files
+ chr :1, // - get character this number represents
+ chroot :1, // - make directory new root for path lookups
+ close :1, // - close file (or pipe or socket) handle
+ closedir :1, // - close directory handle
+ connect :1, // - connect to a remote socket
+ 'continue' :[1,1], // - optional trailing block in a while or foreach
+ 'cos' :1, // - cosine function
+ crypt :1, // - one-way passwd-style encryption
+ dbmclose :1, // - breaks binding on a tied dbm file
+ dbmopen :1, // - create binding on a tied dbm file
+ 'default' :1, //
+ defined :1, // - test whether a value, variable, or function is defined
+ 'delete' :1, // - deletes a value from a hash
+ die :1, // - raise an exception or bail out
+ 'do' :1, // - turn a BLOCK into a TERM
+ dump :1, // - create an immediate core dump
+ each :1, // - retrieve the next key/value pair from a hash
+ endgrent :1, // - be done using group file
+ endhostent :1, // - be done using hosts file
+ endnetent :1, // - be done using networks file
+ endprotoent :1, // - be done using protocols file
+ endpwent :1, // - be done using passwd file
+ endservent :1, // - be done using services file
+ eof :1, // - test a filehandle for its end
+ 'eval' :1, // - catch exceptions or compile and run code
+ 'exec' :1, // - abandon this program to run another
+ exists :1, // - test whether a hash key is present
+ exit :1, // - terminate this program
+ 'exp' :1, // - raise I to a power
+ fcntl :1, // - file control system call
+ fileno :1, // - return file descriptor from filehandle
+ flock :1, // - lock an entire file with an advisory lock
+ fork :1, // - create a new process just like this one
+ format :1, // - declare a picture format with use by the write() function
+ formline :1, // - internal function used for formats
+ getc :1, // - get the next character from the filehandle
+ getgrent :1, // - get next group record
+ getgrgid :1, // - get group record given group user ID
+ getgrnam :1, // - get group record given group name
+ gethostbyaddr :1, // - get host record given its address
+ gethostbyname :1, // - get host record given name
+ gethostent :1, // - get next hosts record
+ getlogin :1, // - return who logged in at this tty
+ getnetbyaddr :1, // - get network record given its address
+ getnetbyname :1, // - get networks record given name
+ getnetent :1, // - get next networks record
+ getpeername :1, // - find the other end of a socket connection
+ getpgrp :1, // - get process group
+ getppid :1, // - get parent process ID
+ getpriority :1, // - get current nice value
+ getprotobyname :1, // - get protocol record given name
+ getprotobynumber :1, // - get protocol record numeric protocol
+ getprotoent :1, // - get next protocols record
+ getpwent :1, // - get next passwd record
+ getpwnam :1, // - get passwd record given user login name
+ getpwuid :1, // - get passwd record given user ID
+ getservbyname :1, // - get services record given its name
+ getservbyport :1, // - get services record given numeric port
+ getservent :1, // - get next services record
+ getsockname :1, // - retrieve the sockaddr for a given socket
+ getsockopt :1, // - get socket options on a given socket
+ given :1, //
+ glob :1, // - expand filenames using wildcards
+ gmtime :1, // - convert UNIX time into record or string using Greenwich time
+ 'goto' :1, // - create spaghetti code
+ grep :1, // - locate elements in a list test true against a given criterion
+ hex :1, // - convert a string to a hexadecimal number
+ 'import' :1, // - patch a module's namespace into your own
+ index :1, // - find a substring within a string
+ 'int' :1, // - get the integer portion of a number
+ ioctl :1, // - system-dependent device control system call
+ 'join' :1, // - join a list into a string using a separator
+ keys :1, // - retrieve list of indices from a hash
+ kill :1, // - send a signal to a process or process group
+ last :1, // - exit a block prematurely
+ lc :1, // - return lower-case version of a string
+ lcfirst :1, // - return a string with just the next letter in lower case
+ length :1, // - return the number of bytes in a string
+ 'link' :1, // - create a hard link in the filesytem
+ listen :1, // - register your socket as a server
+ local : 2, // - create a temporary value for a global variable (dynamic scoping)
+ localtime :1, // - convert UNIX time into record or string using local time
+ lock :1, // - get a thread lock on a variable, subroutine, or method
+ 'log' :1, // - retrieve the natural logarithm for a number
+ lstat :1, // - stat a symbolic link
+ m :null, // - match a string with a regular expression pattern
+ map :1, // - apply a change to a list to get back a new list with the changes
+ mkdir :1, // - create a directory
+ msgctl :1, // - SysV IPC message control operations
+ msgget :1, // - get SysV IPC message queue
+ msgrcv :1, // - receive a SysV IPC message from a message queue
+ msgsnd :1, // - send a SysV IPC message to a message queue
+ my : 2, // - declare and assign a local variable (lexical scoping)
+ 'new' :1, //
+ next :1, // - iterate a block prematurely
+ no :1, // - unimport some module symbols or semantics at compile time
+ oct :1, // - convert a string to an octal number
+ open :1, // - open a file, pipe, or descriptor
+ opendir :1, // - open a directory
+ ord :1, // - find a character's numeric representation
+ our : 2, // - declare and assign a package variable (lexical scoping)
+ pack :1, // - convert a list into a binary representation
+ 'package' :1, // - declare a separate global namespace
+ pipe :1, // - open a pair of connected filehandles
+ pop :1, // - remove the last element from an array and return it
+ pos :1, // - find or set the offset for the last/next m//g search
+ print :1, // - output a list to a filehandle
+ printf :1, // - output a formatted list to a filehandle
+ prototype :1, // - get the prototype (if any) of a subroutine
+ push :1, // - append one or more elements to an array
+ q :null, // - singly quote a string
+ qq :null, // - doubly quote a string
+ qr :null, // - Compile pattern
+ quotemeta :null, // - quote regular expression magic characters
+ qw :null, // - quote a list of words
+ qx :null, // - backquote quote a string
+ rand :1, // - retrieve the next pseudorandom number
+ read :1, // - fixed-length buffered input from a filehandle
+ readdir :1, // - get a directory from a directory handle
+ readline :1, // - fetch a record from a file
+ readlink :1, // - determine where a symbolic link is pointing
+ readpipe :1, // - execute a system command and collect standard output
+ recv :1, // - receive a message over a Socket
+ redo :1, // - start this loop iteration over again
+ ref :1, // - find out the type of thing being referenced
+ rename :1, // - change a filename
+ require :1, // - load in external functions from a library at runtime
+ reset :1, // - clear all variables of a given name
+ 'return' :1, // - get out of a function early
+ reverse :1, // - flip a string or a list
+ rewinddir :1, // - reset directory handle
+ rindex :1, // - right-to-left substring search
+ rmdir :1, // - remove a directory
+ s :null, // - replace a pattern with a string
+ say :1, // - print with newline
+ scalar :1, // - force a scalar context
+ seek :1, // - reposition file pointer for random-access I/O
+ seekdir :1, // - reposition directory pointer
+ select :1, // - reset default output or do I/O multiplexing
+ semctl :1, // - SysV semaphore control operations
+ semget :1, // - get set of SysV semaphores
+ semop :1, // - SysV semaphore operations
+ send :1, // - send a message over a socket
+ setgrent :1, // - prepare group file for use
+ sethostent :1, // - prepare hosts file for use
+ setnetent :1, // - prepare networks file for use
+ setpgrp :1, // - set the process group of a process
+ setpriority :1, // - set a process's nice value
+ setprotoent :1, // - prepare protocols file for use
+ setpwent :1, // - prepare passwd file for use
+ setservent :1, // - prepare services file for use
+ setsockopt :1, // - set some socket options
+ shift :1, // - remove the first element of an array, and return it
+ shmctl :1, // - SysV shared memory operations
+ shmget :1, // - get SysV shared memory segment identifier
+ shmread :1, // - read SysV shared memory
+ shmwrite :1, // - write SysV shared memory
+ shutdown :1, // - close down just half of a socket connection
+ 'sin' :1, // - return the sine of a number
+ sleep :1, // - block for some number of seconds
+ socket :1, // - create a socket
+ socketpair :1, // - create a pair of sockets
+ 'sort' :1, // - sort a list of values
+ splice :1, // - add or remove elements anywhere in an array
+ 'split' :1, // - split up a string using a regexp delimiter
+ sprintf :1, // - formatted print into a string
+ 'sqrt' :1, // - square root function
+ srand :1, // - seed the random number generator
+ stat :1, // - get a file's status information
+ state :1, // - declare and assign a state variable (persistent lexical scoping)
+ study :1, // - optimize input data for repeated searches
+ 'sub' :1, // - declare a subroutine, possibly anonymously
+ 'substr' :1, // - get or alter a portion of a stirng
+ symlink :1, // - create a symbolic link to a file
+ syscall :1, // - execute an arbitrary system call
+ sysopen :1, // - open a file, pipe, or descriptor
+ sysread :1, // - fixed-length unbuffered input from a filehandle
+ sysseek :1, // - position I/O pointer on handle used with sysread and syswrite
+ system :1, // - run a separate program
+ syswrite :1, // - fixed-length unbuffered output to a filehandle
+ tell :1, // - get current seekpointer on a filehandle
+ telldir :1, // - get current seekpointer on a directory handle
+ tie :1, // - bind a variable to an object class
+ tied :1, // - get a reference to the object underlying a tied variable
+ time :1, // - return number of seconds since 1970
+ times :1, // - return elapsed time for self and child processes
+ tr :null, // - transliterate a string
+ truncate :1, // - shorten a file
+ uc :1, // - return upper-case version of a string
+ ucfirst :1, // - return a string with just the next letter in upper case
+ umask :1, // - set file creation mode mask
+ undef :1, // - remove a variable or function definition
+ unlink :1, // - remove one link to a file
+ unpack :1, // - convert binary structure into normal perl variables
+ unshift :1, // - prepend more elements to the beginning of a list
+ untie :1, // - break a tie binding to a variable
+ use :1, // - load in a module at compile time
+ utime :1, // - set a file's last access and modify times
+ values :1, // - return a list of the values in a hash
+ vec :1, // - test or set particular bits in a string
+ wait :1, // - wait for any child process to die
+ waitpid :1, // - wait for a particular child process to die
+ wantarray :1, // - get void vs scalar vs list context of current subroutine call
+ warn :1, // - print debugging info
+ when :1, //
+ write :1, // - print a picture record
+ y :null}; // - transliterate a string
+
+ var RXstyle="string-2";
+ var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
+
+ function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
+ state.chain=null; // 12 3tail
+ state.style=null;
+ state.tail=null;
+ state.tokenize=function(stream,state){
+ var e=false,c,i=0;
+ while(c=stream.next()){
+ if(c===chain[i]&&!e){
+ if(chain[++i]!==undefined){
+ state.chain=chain[i];
+ state.style=style;
+ state.tail=tail}
+ else if(tail)
+ stream.eatWhile(tail);
+ state.tokenize=tokenPerl;
+ return style}
+ e=!e&&c=="\\"}
+ return style};
+ return state.tokenize(stream,state)}
+
+ function tokenSOMETHING(stream,state,string){
+ state.tokenize=function(stream,state){
+ if(stream.string==string)
+ state.tokenize=tokenPerl;
+ stream.skipToEnd();
+ return "string"};
+ return state.tokenize(stream,state)}
+
+ function tokenPerl(stream,state){
+ if(stream.eatSpace())
+ return null;
+ if(state.chain)
+ return tokenChain(stream,state,state.chain,state.style,state.tail);
+ if(stream.match(/^\-?[\d\.]/,false))
+ if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
+ return 'number';
+ if(stream.match(/^<<(?=\w)/)){ // NOTE: <"],RXstyle,RXmodifiers)}
+ if(/[\^'"!~\/]/.test(c)){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}}
+ else if(c=="q"){
+ c=stream.look(1);
+ if(c=="("){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[")"],"string")}
+ if(c=="["){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["]"],"string")}
+ if(c=="{"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["}"],"string")}
+ if(c=="<"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[">"],"string")}
+ if(/[\^'"!~\/]/.test(c)){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[stream.eat(c)],"string")}}
+ else if(c=="w"){
+ c=stream.look(1);
+ if(c=="("){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[")"],"bracket")}
+ if(c=="["){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["]"],"bracket")}
+ if(c=="{"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["}"],"bracket")}
+ if(c=="<"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[">"],"bracket")}
+ if(/[\^'"!~\/]/.test(c)){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[stream.eat(c)],"bracket")}}
+ else if(c=="r"){
+ c=stream.look(1);
+ if(c=="("){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)}
+ if(c=="["){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)}
+ if(c=="{"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)}
+ if(c=="<"){
+ stream.eatSuffix(2);
+ return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}
+ if(/[\^'"!~\/]/.test(c)){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}}
+ else if(/[\^'"!~\/(\[{<]/.test(c)){
+ if(c=="("){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[")"],"string")}
+ if(c=="["){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,["]"],"string")}
+ if(c=="{"){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,["}"],"string")}
+ if(c=="<"){
+ stream.eatSuffix(1);
+ return tokenChain(stream,state,[">"],"string")}
+ if(/[\^'"!~\/]/.test(c)){
+ return tokenChain(stream,state,[stream.eat(c)],"string")}}}}
+ if(ch=="m"){
+ var c=stream.look(-2);
+ if(!(c&&/\w/.test(c))){
+ c=stream.eat(/[(\[{<\^'"!~\/]/);
+ if(c){
+ if(/[\^'"!~\/]/.test(c)){
+ return tokenChain(stream,state,[c],RXstyle,RXmodifiers)}
+ if(c=="("){
+ return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)}
+ if(c=="["){
+ return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)}
+ if(c=="{"){
+ return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)}
+ if(c=="<"){
+ return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}}}}
+ if(ch=="s"){
+ var c=/[\/>\]})\w]/.test(stream.look(-2));
+ if(!c){
+ c=stream.eat(/[(\[{<\^'"!~\/]/);
+ if(c){
+ if(c=="[")
+ return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+ if(c=="{")
+ return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+ if(c=="<")
+ return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+ if(c=="(")
+ return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+ return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}
+ if(ch=="y"){
+ var c=/[\/>\]})\w]/.test(stream.look(-2));
+ if(!c){
+ c=stream.eat(/[(\[{<\^'"!~\/]/);
+ if(c){
+ if(c=="[")
+ return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+ if(c=="{")
+ return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+ if(c=="<")
+ return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+ if(c=="(")
+ return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+ return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}
+ if(ch=="t"){
+ var c=/[\/>\]})\w]/.test(stream.look(-2));
+ if(!c){
+ c=stream.eat("r");if(c){
+ c=stream.eat(/[(\[{<\^'"!~\/]/);
+ if(c){
+ if(c=="[")
+ return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+ if(c=="{")
+ return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+ if(c=="<")
+ return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+ if(c=="(")
+ return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+ return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}}
+ if(ch=="`"){
+ return tokenChain(stream,state,[ch],"variable-2")}
+ if(ch=="/"){
+ if(!/~\s*$/.test(stream.prefix()))
+ return "operator";
+ else
+ return tokenChain(stream,state,[ch],RXstyle,RXmodifiers)}
+ if(ch=="$"){
+ var p=stream.pos;
+ if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
+ return "variable-2";
+ else
+ stream.pos=p}
+ if(/[$@%]/.test(ch)){
+ var p=stream.pos;
+ if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
+ var c=stream.current();
+ if(PERL[c])
+ return "variable-2"}
+ stream.pos=p}
+ if(/[$@%&]/.test(ch)){
+ if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
+ var c=stream.current();
+ if(PERL[c])
+ return "variable-2";
+ else
+ return "variable"}}
+ if(ch=="#"){
+ if(stream.look(-2)!="$"){
+ stream.skipToEnd();
+ return "comment"}}
+ if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
+ var p=stream.pos;
+ stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
+ if(PERL[stream.current()])
+ return "operator";
+ else
+ stream.pos=p}
+ if(ch=="_"){
+ if(stream.pos==1){
+ if(stream.suffix(6)=="_END__"){
+ return tokenChain(stream,state,['\0'],"comment")}
+ else if(stream.suffix(7)=="_DATA__"){
+ return tokenChain(stream,state,['\0'],"variable-2")}
+ else if(stream.suffix(7)=="_C__"){
+ return tokenChain(stream,state,['\0'],"string")}}}
+ if(/\w/.test(ch)){
+ var p=stream.pos;
+ if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}"))
+ return "string";
+ else
+ stream.pos=p}
+ if(/[A-Z]/.test(ch)){
+ var l=stream.look(-2);
+ var p=stream.pos;
+ stream.eatWhile(/[A-Z_]/);
+ if(/[\da-z]/.test(stream.look(0))){
+ stream.pos=p}
+ else{
+ var c=PERL[stream.current()];
+ if(!c)
+ return "meta";
+ if(c[1])
+ c=c[0];
+ if(l!=":"){
+ if(c==1)
+ return "keyword";
+ else if(c==2)
+ return "def";
+ else if(c==3)
+ return "atom";
+ else if(c==4)
+ return "operator";
+ else if(c==5)
+ return "variable-2";
+ else
+ return "meta"}
+ else
+ return "meta"}}
+ if(/[a-zA-Z_]/.test(ch)){
+ var l=stream.look(-2);
+ stream.eatWhile(/\w/);
+ var c=PERL[stream.current()];
+ if(!c)
+ return "meta";
+ if(c[1])
+ c=c[0];
+ if(l!=":"){
+ if(c==1)
+ return "keyword";
+ else if(c==2)
+ return "def";
+ else if(c==3)
+ return "atom";
+ else if(c==4)
+ return "operator";
+ else if(c==5)
+ return "variable-2";
+ else
+ return "meta"}
+ else
+ return "meta"}
+ return null}
+
+ return{
+ startState:function(){
+ return{
+ tokenize:tokenPerl,
+ chain:null,
+ style:null,
+ tail:null}},
+ token:function(stream,state){
+ return (state.tokenize||tokenPerl)(stream,state)},
+ electricChars:"{}"}});
+
+CodeMirror.defineMIME("text/x-perl", "perl");
+
+// it's like "peek", but need for look-ahead or look-behind if index < 0
+CodeMirror.StringStream.prototype.look=function(c){
+ return this.string.charAt(this.pos+(c||0))};
+
+// return a part of prefix of current stream from current position
+CodeMirror.StringStream.prototype.prefix=function(c){
+ if(c){
+ var x=this.pos-c;
+ return this.string.substr((x>=0?x:0),c)}
+ else{
+ return this.string.substr(0,this.pos-1)}};
+
+// return a part of suffix of current stream from current position
+CodeMirror.StringStream.prototype.suffix=function(c){
+ var y=this.string.length;
+ var x=y-this.pos+1;
+ return this.string.substr(this.pos,(c&&c=(y=this.string.length-1))
+ this.pos=y;
+ else
+ this.pos=x};
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/php/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/php/index.html
new file mode 100644
index 0000000000..7949044e65
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/php/index.html
@@ -0,0 +1,48 @@
+
+
+
+ CodeMirror: PHP mode
+
+
+
+
+
+
+
+
+
+
+
+
CodeMirror: PHP mode
+
+
+
+
+
+
Simple HTML/PHP mode based on
+ the C-like mode. Depends on XML,
+ JavaScript, CSS, and C-like modes.
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/properties/properties.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/properties/properties.js
new file mode 100644
index 0000000000..d3a13c765d
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/properties/properties.js
@@ -0,0 +1,63 @@
+CodeMirror.defineMode("properties", function() {
+ return {
+ token: function(stream, state) {
+ var sol = stream.sol() || state.afterSection;
+ var eol = stream.eol();
+
+ state.afterSection = false;
+
+ if (sol) {
+ if (state.nextMultiline) {
+ state.inMultiline = true;
+ state.nextMultiline = false;
+ } else {
+ state.position = "def";
+ }
+ }
+
+ if (eol && ! state.nextMultiline) {
+ state.inMultiline = false;
+ state.position = "def";
+ }
+
+ if (sol) {
+ while(stream.eatSpace());
+ }
+
+ var ch = stream.next();
+
+ if (sol && (ch === "#" || ch === "!" || ch === ";")) {
+ state.position = "comment";
+ stream.skipToEnd();
+ return "comment";
+ } else if (sol && ch === "[") {
+ state.afterSection = true;
+ stream.skipTo("]"); stream.eat("]");
+ return "header";
+ } else if (ch === "=" || ch === ":") {
+ state.position = "quote";
+ return null;
+ } else if (ch === "\\" && state.position === "quote") {
+ if (stream.next() !== "u") { // u = Unicode sequence \u1234
+ // Multiline value
+ state.nextMultiline = true;
+ }
+ }
+
+ return state.position;
+ },
+
+ startState: function() {
+ return {
+ position : "def", // Current position, "def", "quote" or "comment"
+ nextMultiline : false, // Is the next line multiline value
+ inMultiline : false, // Is the current line a multiline value
+ afterSection : false // Did we just open a section
+ };
+ }
+
+ };
+});
+
+CodeMirror.defineMIME("text/x-properties", "properties");
+CodeMirror.defineMIME("text/x-ini", "properties");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/LICENSE.txt b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/LICENSE.txt
new file mode 100644
index 0000000000..918866b42a
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/index.html
new file mode 100644
index 0000000000..47e0e9d071
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/index.html
@@ -0,0 +1,122 @@
+
+
+
+ CodeMirror: Python mode
+
+
+
+
+
+
+
+
CodeMirror: Python mode
+
+
+
+
Configuration Options:
+
+
version - 2/3 - The version of Python to recognize. Default is 2.
+
singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.
+
+
+
MIME types defined:text/x-python.
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/python.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/python.js
new file mode 100644
index 0000000000..d6888e8e58
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/python/python.js
@@ -0,0 +1,338 @@
+CodeMirror.defineMode("python", function(conf, parserConf) {
+ var ERRORCLASS = 'error';
+
+ function wordRegexp(words) {
+ return new RegExp("^((" + words.join(")|(") + "))\\b");
+ }
+
+ var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
+ var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+ var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+ var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+ var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+ var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+
+ var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
+ var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
+ 'def', 'del', 'elif', 'else', 'except', 'finally',
+ 'for', 'from', 'global', 'if', 'import',
+ 'lambda', 'pass', 'raise', 'return',
+ 'try', 'while', 'with', 'yield'];
+ var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
+ 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
+ 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
+ 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
+ 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
+ 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
+ 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
+ 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
+ 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
+ 'type', 'vars', 'zip', '__import__', 'NotImplemented',
+ 'Ellipsis', '__debug__'];
+ var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
+ 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
+ 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
+ 'keywords': ['exec', 'print']};
+ var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
+ 'keywords': ['nonlocal', 'False', 'True', 'None']};
+
+ if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
+ commonkeywords = commonkeywords.concat(py3.keywords);
+ commonBuiltins = commonBuiltins.concat(py3.builtins);
+ var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
+ } else {
+ commonkeywords = commonkeywords.concat(py2.keywords);
+ commonBuiltins = commonBuiltins.concat(py2.builtins);
+ var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
+ }
+ var keywords = wordRegexp(commonkeywords);
+ var builtins = wordRegexp(commonBuiltins);
+
+ var indentInfo = null;
+
+ // tokenizers
+ function tokenBase(stream, state) {
+ // Handle scope changes
+ if (stream.sol()) {
+ var scopeOffset = state.scopes[0].offset;
+ if (stream.eatSpace()) {
+ var lineOffset = stream.indentation();
+ if (lineOffset > scopeOffset) {
+ indentInfo = 'indent';
+ } else if (lineOffset < scopeOffset) {
+ indentInfo = 'dedent';
+ }
+ return null;
+ } else {
+ if (scopeOffset > 0) {
+ dedent(stream, state);
+ }
+ }
+ }
+ if (stream.eatSpace()) {
+ return null;
+ }
+
+ var ch = stream.peek();
+
+ // Handle Comments
+ if (ch === '#') {
+ stream.skipToEnd();
+ return 'comment';
+ }
+
+ // Handle Number Literals
+ if (stream.match(/^[0-9\.]/, false)) {
+ var floatLiteral = false;
+ // Floats
+ if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
+ if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
+ if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+ if (floatLiteral) {
+ // Float literals may be "imaginary"
+ stream.eat(/J/i);
+ return 'number';
+ }
+ // Integers
+ var intLiteral = false;
+ // Hex
+ if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
+ // Binary
+ if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
+ // Octal
+ if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
+ // Decimal
+ if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
+ // Decimal literals may be "imaginary"
+ stream.eat(/J/i);
+ // TODO - Can you have imaginary longs?
+ intLiteral = true;
+ }
+ // Zero by itself with no other piece of number.
+ if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+ if (intLiteral) {
+ // Integer literals may be "long"
+ stream.eat(/L/i);
+ return 'number';
+ }
+ }
+
+ // Handle Strings
+ if (stream.match(stringPrefixes)) {
+ state.tokenize = tokenStringFactory(stream.current());
+ return state.tokenize(stream, state);
+ }
+
+ // Handle operators and Delimiters
+ if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+ return null;
+ }
+ if (stream.match(doubleOperators)
+ || stream.match(singleOperators)
+ || stream.match(wordOperators)) {
+ return 'operator';
+ }
+ if (stream.match(singleDelimiters)) {
+ return null;
+ }
+
+ if (stream.match(keywords)) {
+ return 'keyword';
+ }
+
+ if (stream.match(builtins)) {
+ return 'builtin';
+ }
+
+ if (stream.match(identifiers)) {
+ return 'variable';
+ }
+
+ // Handle non-detected items
+ stream.next();
+ return ERRORCLASS;
+ }
+
+ function tokenStringFactory(delimiter) {
+ while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
+ delimiter = delimiter.substr(1);
+ }
+ var singleline = delimiter.length == 1;
+ var OUTCLASS = 'string';
+
+ return function tokenString(stream, state) {
+ while (!stream.eol()) {
+ stream.eatWhile(/[^'"\\]/);
+ if (stream.eat('\\')) {
+ stream.next();
+ if (singleline && stream.eol()) {
+ return OUTCLASS;
+ }
+ } else if (stream.match(delimiter)) {
+ state.tokenize = tokenBase;
+ return OUTCLASS;
+ } else {
+ stream.eat(/['"]/);
+ }
+ }
+ if (singleline) {
+ if (parserConf.singleLineStringErrors) {
+ return ERRORCLASS;
+ } else {
+ state.tokenize = tokenBase;
+ }
+ }
+ return OUTCLASS;
+ };
+ }
+
+ function indent(stream, state, type) {
+ type = type || 'py';
+ var indentUnit = 0;
+ if (type === 'py') {
+ if (state.scopes[0].type !== 'py') {
+ state.scopes[0].offset = stream.indentation();
+ return;
+ }
+ for (var i = 0; i < state.scopes.length; ++i) {
+ if (state.scopes[i].type === 'py') {
+ indentUnit = state.scopes[i].offset + conf.indentUnit;
+ break;
+ }
+ }
+ } else {
+ indentUnit = stream.column() + stream.current().length;
+ }
+ state.scopes.unshift({
+ offset: indentUnit,
+ type: type
+ });
+ }
+
+ function dedent(stream, state, type) {
+ type = type || 'py';
+ if (state.scopes.length == 1) return;
+ if (state.scopes[0].type === 'py') {
+ var _indent = stream.indentation();
+ var _indent_index = -1;
+ for (var i = 0; i < state.scopes.length; ++i) {
+ if (_indent === state.scopes[i].offset) {
+ _indent_index = i;
+ break;
+ }
+ }
+ if (_indent_index === -1) {
+ return true;
+ }
+ while (state.scopes[0].offset !== _indent) {
+ state.scopes.shift();
+ }
+ return false
+ } else {
+ if (type === 'py') {
+ state.scopes[0].offset = stream.indentation();
+ return false;
+ } else {
+ if (state.scopes[0].type != type) {
+ return true;
+ }
+ state.scopes.shift();
+ return false;
+ }
+ }
+ }
+
+ function tokenLexer(stream, state) {
+ indentInfo = null;
+ var style = state.tokenize(stream, state);
+ var current = stream.current();
+
+ // Handle '.' connected identifiers
+ if (current === '.') {
+ style = stream.match(identifiers, false) ? null : ERRORCLASS;
+ if (style === null && state.lastToken === 'meta') {
+ // Apply 'meta' style to '.' connected identifiers when
+ // appropriate.
+ style = 'meta';
+ }
+ return style;
+ }
+
+ // Handle decorators
+ if (current === '@') {
+ return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
+ }
+
+ if ((style === 'variable' || style === 'builtin')
+ && state.lastToken === 'meta') {
+ style = 'meta';
+ }
+
+ // Handle scope changes.
+ if (current === 'pass' || current === 'return') {
+ state.dedent += 1;
+ }
+ if (current === 'lambda') state.lambda = true;
+ if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
+ || indentInfo === 'indent') {
+ indent(stream, state);
+ }
+ var delimiter_index = '[({'.indexOf(current);
+ if (delimiter_index !== -1) {
+ indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+ }
+ if (indentInfo === 'dedent') {
+ if (dedent(stream, state)) {
+ return ERRORCLASS;
+ }
+ }
+ delimiter_index = '])}'.indexOf(current);
+ if (delimiter_index !== -1) {
+ if (dedent(stream, state, current)) {
+ return ERRORCLASS;
+ }
+ }
+ if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
+ if (state.scopes.length > 1) state.scopes.shift();
+ state.dedent -= 1;
+ }
+
+ return style;
+ }
+
+ var external = {
+ startState: function(basecolumn) {
+ return {
+ tokenize: tokenBase,
+ scopes: [{offset:basecolumn || 0, type:'py'}],
+ lastToken: null,
+ lambda: false,
+ dedent: 0
+ };
+ },
+
+ token: function(stream, state) {
+ var style = tokenLexer(stream, state);
+
+ state.lastToken = style;
+
+ if (stream.eol() && stream.lambda) {
+ state.lambda = false;
+ }
+
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase) {
+ return 0;
+ }
+
+ return state.scopes[0].offset;
+ }
+
+ };
+ return external;
+});
+
+CodeMirror.defineMIME("text/x-python", "python");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/LICENSE b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/LICENSE
new file mode 100644
index 0000000000..2510ae16cf
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the Ubalo, Inc nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/index.html
new file mode 100644
index 0000000000..69775055de
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/index.html
@@ -0,0 +1,73 @@
+
+
+
+ CodeMirror: R mode
+
+
+
+
+
+
+
+
CodeMirror: R mode
+
+
+
+
MIME types defined:text/x-rsrc.
+
+
Development of the CodeMirror R mode was kindly sponsored
+ by Ubalo, who hold
+ the license.
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/r.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/r.js
new file mode 100644
index 0000000000..53647f23fa
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/r/r.js
@@ -0,0 +1,141 @@
+CodeMirror.defineMode("r", function(config) {
+ function wordObj(str) {
+ var words = str.split(" "), res = {};
+ for (var i = 0; i < words.length; ++i) res[words[i]] = true;
+ return res;
+ }
+ var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
+ var builtins = wordObj("list quote bquote eval return call parse deparse");
+ var keywords = wordObj("if else repeat while function for in next break");
+ var blockkeywords = wordObj("if else repeat while function for");
+ var opChars = /[+\-*\/^<>=!&|~$:]/;
+ var curPunc;
+
+ function tokenBase(stream, state) {
+ curPunc = null;
+ var ch = stream.next();
+ if (ch == "#") {
+ stream.skipToEnd();
+ return "comment";
+ } else if (ch == "0" && stream.eat("x")) {
+ stream.eatWhile(/[\da-f]/i);
+ return "number";
+ } else if (ch == "." && stream.eat(/\d/)) {
+ stream.match(/\d*(?:e[+\-]?\d+)?/);
+ return "number";
+ } else if (/\d/.test(ch)) {
+ stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
+ return "number";
+ } else if (ch == "'" || ch == '"') {
+ state.tokenize = tokenString(ch);
+ return "string";
+ } else if (ch == "." && stream.match(/.[.\d]+/)) {
+ return "keyword";
+ } else if (/[\w\.]/.test(ch) && ch != "_") {
+ stream.eatWhile(/[\w\.]/);
+ var word = stream.current();
+ if (atoms.propertyIsEnumerable(word)) return "atom";
+ if (keywords.propertyIsEnumerable(word)) {
+ if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block";
+ return "keyword";
+ }
+ if (builtins.propertyIsEnumerable(word)) return "builtin";
+ return "variable";
+ } else if (ch == "%") {
+ if (stream.skipTo("%")) stream.next();
+ return "variable-2";
+ } else if (ch == "<" && stream.eat("-")) {
+ return "arrow";
+ } else if (ch == "=" && state.ctx.argList) {
+ return "arg-is";
+ } else if (opChars.test(ch)) {
+ if (ch == "$") return "dollar";
+ stream.eatWhile(opChars);
+ return "operator";
+ } else if (/[\(\){}\[\];]/.test(ch)) {
+ curPunc = ch;
+ if (ch == ";") return "semi";
+ return null;
+ } else {
+ return null;
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ if (stream.eat("\\")) {
+ var ch = stream.next();
+ if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
+ else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
+ else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
+ else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
+ else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
+ return "string-2";
+ } else {
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next == quote) { state.tokenize = tokenBase; break; }
+ if (next == "\\") { stream.backUp(1); break; }
+ }
+ return "string";
+ }
+ };
+ }
+
+ function push(state, type, stream) {
+ state.ctx = {type: type,
+ indent: state.indent,
+ align: null,
+ column: stream.column(),
+ prev: state.ctx};
+ }
+ function pop(state) {
+ state.indent = state.ctx.indent;
+ state.ctx = state.ctx.prev;
+ }
+
+ return {
+ startState: function(base) {
+ return {tokenize: tokenBase,
+ ctx: {type: "top",
+ indent: -config.indentUnit,
+ align: false},
+ indent: 0,
+ afterIdent: false};
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (state.ctx.align == null) state.ctx.align = false;
+ state.indent = stream.indentation();
+ }
+ if (stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
+
+ var ctype = state.ctx.type;
+ if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
+ if (curPunc == "{") push(state, "}", stream);
+ else if (curPunc == "(") {
+ push(state, ")", stream);
+ if (state.afterIdent) state.ctx.argList = true;
+ }
+ else if (curPunc == "[") push(state, "]", stream);
+ else if (curPunc == "block") push(state, "block", stream);
+ else if (curPunc == ctype) pop(state);
+ state.afterIdent = style == "variable" || style == "keyword";
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
+ closing = firstChar == ctx.type;
+ if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
+ else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+ else return ctx.indent + (closing ? 0 : config.indentUnit);
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/x-rsrc", "r");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/LICENSE b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/LICENSE
new file mode 100644
index 0000000000..977e284e0f
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/LICENSE
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2011 Jeff Pickhardt
+Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/index.html
new file mode 100644
index 0000000000..6e2b71d7a6
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/index.html
@@ -0,0 +1,727 @@
+
+
+
+ CodeMirror: Razor mode
+
+
+
+
+
+
+
+
CodeMirror: Razor mode
+
+
+
+
MIME types defined:text/x-coffeescript.
+
+
The CoffeeScript mode was written by Jeff Pickhardt (license).
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/razor.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/razor.js
new file mode 100644
index 0000000000..3907b97dd9
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/razor/razor.js
@@ -0,0 +1,254 @@
+CodeMirror.defineMode("razor", function(config, parserConfig) {
+ var indentUnit = config.indentUnit,
+ keywords = words("abstract as base break case catch checked class const continue" +
+ " default delegate do else enum event explicit extern finally fixed for" +
+ " foreach goto if implicit in interface internal is lock namespace new" +
+ " operator out override params private protected public readonly ref return sealed" +
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+ " global group into join let orderby partial remove select set value var yield"),
+
+ builtin = words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+ " Guid Int16 Int32 Int64 Library Model Object SByte Single String TimeSpan UInt16 UInt32" +
+ " UInt64 bool byte char decimal double short int long object" +
+ " sbyte float string ushort uint ulong"),
+ blockKeywords = words("catch class do else finally for foreach if struct switch try while"),
+ atoms = words("true false null"),
+ hooks = parserConfig.hooks || {},
+ multiLineStrings = parserConfig.multiLineStrings;
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+ var curPunc;
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (hooks[ch]) {
+ var result = hooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ curPunc = ch;
+ return null;
+ }
+ if (/\d/.test(ch)) {
+ stream.eatWhile(/[\w\.]/);
+ return "number";
+ }
+ if (ch == "@") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ }
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+
+ return "at";
+ }
+
+ if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return "operator";
+ }
+ stream.eatWhile(/[\w\$_]/);
+ var cur = stream.current();
+ if (keywords.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "keyword";
+ }
+ if (builtin.propertyIsEnumerable(cur)) {
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+ return "builtin";
+ }
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
+ return "variable";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {end = true; break;}
+ escaped = !escaped && next == "\\";
+ }
+ if (end || !(escaped || multiLineStrings))
+ state.tokenize = null;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "@" && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ function Context(indented, column, type, align, prev) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.align = align;
+ this.prev = prev;
+ }
+ function pushContext(state, col, type) {
+ return state.context = new Context(state.indented, col, type, null, state.context);
+ }
+ function popContext(state) {
+ var t = state.context.type;
+ if (t == ")" || t == "]" || t == "}")
+ state.indented = state.context.indented;
+ return state.context = state.context.prev;
+ }
+
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {
+ tokenize: null,
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+ indented: 0,
+ startOfLine: true
+ };
+ },
+
+ token: function(stream, state) {
+ var ctx = state.context;
+ if (stream.sol()) {
+ if (ctx.align == null) ctx.align = false;
+ state.indented = stream.indentation();
+ state.startOfLine = true;
+ }
+ if (stream.eatSpace()) return null;
+ curPunc = null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style == "comment" || style == "meta") return style;
+ if (ctx.align == null) ctx.align = true;
+
+ if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
+ else if (curPunc == "}") {
+ while (ctx.type == "statement") ctx = popContext(state);
+ if (ctx.type == "}") ctx = popContext(state);
+ while (ctx.type == "statement") ctx = popContext(state);
+ }
+ else if (curPunc == ctx.type) popContext(state);
+ else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+ pushContext(state, stream.column(), "statement");
+ state.startOfLine = false;
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+ if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+ var closing = firstChar == ctx.type;
+ if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+ else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+ else return ctx.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricChars: "{}"
+ };
+});
+
+(function() {
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+ var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
+ "double static else struct entry switch extern typedef float union for unsigned " +
+ "goto while enum void const signed volatile";
+
+ function cppHook(stream, state) {
+ if (!state.startOfLine) return false;
+ stream.skipToEnd();
+ return "meta";
+ }
+
+ // C#-style strings where "" escapes a quote.
+ function tokenAtString(stream, state) {
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next == '"' && !stream.eat('"')) {
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "string";
+ }
+
+ function mimes(ms, mode) {
+ for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
+ }
+
+/*
+ mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
+ name: "clike",
+ keywords: words(cKeywords),
+ blockKeywords: words("case do else for if switch while struct"),
+ atoms: words("null"),
+ hooks: {"#": cppHook}
+ });
+
+ mimes(["text/x-c++src", "text/x-c++hdr"], {
+ name: "clike",
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
+ "static_cast typeid catch operator template typename class friend private " +
+ "this using const_cast inline public throw virtual delete mutable protected " +
+ "wchar_t"),
+ blockKeywords: words("catch class do else finally for if struct switch try while"),
+ atoms: words("true false null"),
+ hooks: {"#": cppHook}
+ });*/
+
+ CodeMirror.defineMIME("text/x-razor", {
+ name: "razor",
+ keywords: words("abstract as base break case catch checked class const continue" +
+ " default delegate do else enum event explicit extern finally fixed for" +
+ " foreach goto if implicit in interface internal is lock namespace new" +
+ " operator out override params private protected public readonly ref return sealed" +
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+ " global group into join let orderby partial remove select set value var yield"),
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+ builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+ " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
+ " UInt64 bool byte char decimal double short int long object" +
+ " sbyte float string ushort uint ulong"),
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ if (stream.eat('"')) {
+ state.tokenize = tokenAtString;
+ return tokenAtString(stream, state);
+ }
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+
+}());
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/changes.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/changes.js
new file mode 100644
index 0000000000..cb45f9e524
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/changes.js
@@ -0,0 +1,19 @@
+CodeMirror.defineMode("changes", function(config, modeConfig) {
+ var headerSeperator = /^-+$/;
+ var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /;
+ var simpleEmail = /^[\w+.-]+@[\w.-]+/;
+
+ return {
+ token: function(stream) {
+ if (stream.sol()) {
+ if (stream.match(headerSeperator)) { return 'tag'; }
+ if (stream.match(headerLine)) { return 'tag'; }
+ }
+ if (stream.match(simpleEmail)) { return 'string'; }
+ stream.next();
+ return null;
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/x-rpm-changes", "changes");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/index.html
new file mode 100644
index 0000000000..b7ff952d88
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/changes/index.html
@@ -0,0 +1,53 @@
+
+
+
+ CodeMirror: RPM changes mode
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.css b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.css
new file mode 100644
index 0000000000..d0a5d430ca
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.css
@@ -0,0 +1,5 @@
+.cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;}
+.cm-s-default span.cm-macro {color: #b218b2;}
+.cm-s-default span.cm-section {color: green; font-weight: bold;}
+.cm-s-default span.cm-script {color: red;}
+.cm-s-default span.cm-issue {color: yellow;}
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.js
new file mode 100644
index 0000000000..902db6ae1f
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rpm/spec/spec.js
@@ -0,0 +1,66 @@
+// Quick and dirty spec file highlighting
+
+CodeMirror.defineMode("spec", function(config, modeConfig) {
+ var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;
+
+ var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/;
+ var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/;
+ var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
+ var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
+ var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros
+
+ return {
+ startState: function () {
+ return {
+ controlFlow: false,
+ macroParameters: false,
+ section: false
+ };
+ },
+ token: function (stream, state) {
+ var ch = stream.peek();
+ if (ch == "#") { stream.skipToEnd(); return "comment"; }
+
+ if (stream.sol()) {
+ if (stream.match(preamble)) { return "preamble"; }
+ if (stream.match(section)) { return "section"; }
+ }
+
+ if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
+ if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'
+
+ if (stream.match(control_flow_simple)) { return "keyword"; }
+ if (stream.match(control_flow_complex)) {
+ state.controlFlow = true;
+ return "keyword";
+ }
+ if (state.controlFlow) {
+ if (stream.match(operators)) { return "operator"; }
+ if (stream.match(/^(\d+)/)) { return "number"; }
+ if (stream.eol()) { state.controlFlow = false; }
+ }
+
+ if (stream.match(arch)) { return "number"; }
+
+ // Macros like '%make_install' or '%attr(0775,root,root)'
+ if (stream.match(/^%[\w]+/)) {
+ if (stream.match(/^\(/)) { state.macroParameters = true; }
+ return "macro";
+ }
+ if (state.macroParameters) {
+ if (stream.match(/^\d+/)) { return "number";}
+ if (stream.match(/^\)/)) {
+ state.macroParameters = false;
+ return "macro";
+ }
+ }
+ if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}'
+
+ //TODO: Include bash script sub-parser (CodeMirror supports that)
+ stream.next();
+ return null;
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/x-rpm-spec", "spec");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/index.html
new file mode 100644
index 0000000000..fd75a284c0
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/index.html
@@ -0,0 +1,525 @@
+
+
+
+ CodeMirror: reStructuredText mode
+
+
+
+
+
+
+
+
CodeMirror: reStructuredText mode
+
+
+
+
+
The reStructuredText mode supports one configuration parameter:
+
+
verbatim (string)
+
A name or MIME type of a mode that will be used for highlighting
+ verbatim blocks. By default, reStructuredText mode uses uniform color
+ for whole block of verbatim text if no mode is given.
+
+
If python mode is available,
+ it will be used for highlighting blocks containing Python/IPython terminal
+ sessions (blocks starting with >>> (for Python) or
+ In [num]: (for IPython).
+
+
MIME types defined:text/x-rst.
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/rst.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/rst.js
new file mode 100644
index 0000000000..c4ecdf4c75
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/rst/rst.js
@@ -0,0 +1,326 @@
+CodeMirror.defineMode('rst', function(config, options) {
+ function setState(state, fn, ctx) {
+ state.fn = fn;
+ setCtx(state, ctx);
+ }
+
+ function setCtx(state, ctx) {
+ state.ctx = ctx || {};
+ }
+
+ function setNormal(state, ch) {
+ if (ch && (typeof ch !== 'string')) {
+ var str = ch.current();
+ ch = str[str.length-1];
+ }
+
+ setState(state, normal, {back: ch});
+ }
+
+ function hasMode(mode) {
+ if (mode) {
+ var modes = CodeMirror.listModes();
+
+ for (var i in modes) {
+ if (modes[i] == mode) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ function getMode(mode) {
+ if (hasMode(mode)) {
+ return CodeMirror.getMode(config, mode);
+ } else {
+ return null;
+ }
+ }
+
+ var verbatimMode = getMode(options.verbatim);
+ var pythonMode = getMode('python');
+
+ var reSection = /^[!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
+ var reDirective = /^\s*\w([-:.\w]*\w)?::(\s|$)/;
+ var reHyperlink = /^\s*_[\w-]+:(\s|$)/;
+ var reFootnote = /^\s*\[(\d+|#)\](\s|$)/;
+ var reCitation = /^\s*\[[A-Za-z][\w-]*\](\s|$)/;
+ var reFootnoteRef = /^\[(\d+|#)\]_/;
+ var reCitationRef = /^\[[A-Za-z][\w-]*\]_/;
+ var reDirectiveMarker = /^\.\.(\s|$)/;
+ var reVerbatimMarker = /^::\s*$/;
+ var rePreInline = /^[-\s"([{/:.,;!?\\_]/;
+ var reEnumeratedList = /^\s*((\d+|[A-Za-z#])[.)]|\((\d+|[A-Z-a-z#])\))\s/;
+ var reBulletedList = /^\s*[-\+\*]\s/;
+ var reExamples = /^\s+(>>>|In \[\d+\]:)\s/;
+
+ function normal(stream, state) {
+ var ch, sol, i;
+
+ if (stream.eat(/\\/)) {
+ ch = stream.next();
+ setNormal(state, ch);
+ return null;
+ }
+
+ sol = stream.sol();
+
+ if (sol && (ch = stream.eat(reSection))) {
+ for (i = 0; stream.eat(ch); i++);
+
+ if (i >= 3 && stream.match(/^\s*$/)) {
+ setNormal(state, null);
+ return 'header';
+ } else {
+ stream.backUp(i + 1);
+ }
+ }
+
+ if (sol && stream.match(reDirectiveMarker)) {
+ if (!stream.eol()) {
+ setState(state, directive);
+ }
+ return 'meta';
+ }
+
+ if (stream.match(reVerbatimMarker)) {
+ if (!verbatimMode) {
+ setState(state, verbatim);
+ } else {
+ var mode = verbatimMode;
+
+ setState(state, verbatim, {
+ mode: mode,
+ local: mode.startState()
+ });
+ }
+ return 'meta';
+ }
+
+ if (sol && stream.match(reExamples, false)) {
+ if (!pythonMode) {
+ setState(state, verbatim);
+ return 'meta';
+ } else {
+ var mode = pythonMode;
+
+ setState(state, verbatim, {
+ mode: mode,
+ local: mode.startState()
+ });
+
+ return null;
+ }
+ }
+
+ function testBackward(re) {
+ return sol || !state.ctx.back || re.test(state.ctx.back);
+ }
+
+ function testForward(re) {
+ return stream.eol() || stream.match(re, false);
+ }
+
+ function testInline(re) {
+ return stream.match(re) && testBackward(/\W/) && testForward(/\W/);
+ }
+
+ if (testInline(reFootnoteRef)) {
+ setNormal(state, stream);
+ return 'footnote';
+ }
+
+ if (testInline(reCitationRef)) {
+ setNormal(state, stream);
+ return 'citation';
+ }
+
+ ch = stream.next();
+
+ if (testBackward(rePreInline)) {
+ if ((ch === ':' || ch === '|') && stream.eat(/\S/)) {
+ var token;
+
+ if (ch === ':') {
+ token = 'builtin';
+ } else {
+ token = 'atom';
+ }
+
+ setState(state, inline, {
+ ch: ch,
+ wide: false,
+ prev: null,
+ token: token
+ });
+
+ return token;
+ }
+
+ if (ch === '*' || ch === '`') {
+ var orig = ch,
+ wide = false;
+
+ ch = stream.next();
+
+ if (ch == orig) {
+ wide = true;
+ ch = stream.next();
+ }
+
+ if (ch && !/\s/.test(ch)) {
+ var token;
+
+ if (orig === '*') {
+ token = wide ? 'strong' : 'em';
+ } else {
+ token = wide ? 'string' : 'string-2';
+ }
+
+ setState(state, inline, {
+ ch: orig, // inline() has to know what to search for
+ wide: wide, // are we looking for `ch` or `chch`
+ prev: null, // terminator must not be preceeded with whitespace
+ token: token // I don't want to recompute this all the time
+ });
+
+ return token;
+ }
+ }
+ }
+
+ setNormal(state, ch);
+ return null;
+ }
+
+ function inline(stream, state) {
+ var ch = stream.next(),
+ token = state.ctx.token;
+
+ function finish(ch) {
+ state.ctx.prev = ch;
+ return token;
+ }
+
+ if (ch != state.ctx.ch) {
+ return finish(ch);
+ }
+
+ if (/\s/.test(state.ctx.prev)) {
+ return finish(ch);
+ }
+
+ if (state.ctx.wide) {
+ ch = stream.next();
+
+ if (ch != state.ctx.ch) {
+ return finish(ch);
+ }
+ }
+
+ if (!stream.eol() && !rePostInline.test(stream.peek())) {
+ if (state.ctx.wide) {
+ stream.backUp(1);
+ }
+
+ return finish(ch);
+ }
+
+ setState(state, normal);
+ setNormal(state, ch);
+
+ return token;
+ }
+
+ function directive(stream, state) {
+ var token = null;
+
+ if (stream.match(reDirective)) {
+ token = 'attribute';
+ } else if (stream.match(reHyperlink)) {
+ token = 'link';
+ } else if (stream.match(reFootnote)) {
+ token = 'quote';
+ } else if (stream.match(reCitation)) {
+ token = 'quote';
+ } else {
+ stream.eatSpace();
+
+ if (stream.eol()) {
+ setNormal(state, stream);
+ return null;
+ } else {
+ stream.skipToEnd();
+ setState(state, comment);
+ return 'comment';
+ }
+ }
+
+ // FIXME this is unreachable
+ setState(state, body, {start: true});
+ return token;
+ }
+
+ function body(stream, state) {
+ var token = 'body';
+
+ if (!state.ctx.start || stream.sol()) {
+ return block(stream, state, token);
+ }
+
+ stream.skipToEnd();
+ setCtx(state);
+
+ return token;
+ }
+
+ function comment(stream, state) {
+ return block(stream, state, 'comment');
+ }
+
+ function verbatim(stream, state) {
+ if (!verbatimMode) {
+ return block(stream, state, 'meta');
+ } else {
+ if (stream.sol()) {
+ if (!stream.eatSpace()) {
+ setNormal(state, stream);
+ }
+
+ return null;
+ }
+
+ return verbatimMode.token(stream, state.ctx.local);
+ }
+ }
+
+ function block(stream, state, token) {
+ if (stream.eol() || stream.eatSpace()) {
+ stream.skipToEnd();
+ return token;
+ } else {
+ setNormal(state, stream);
+ return null;
+ }
+ }
+
+ return {
+ startState: function() {
+ return {fn: normal, ctx: {}};
+ },
+
+ copyState: function(state) {
+ return {fn: state.fn, ctx: state.ctx};
+ },
+
+ token: function(stream, state) {
+ var token = state.fn(stream, state);
+ return token;
+ }
+ };
+}, "python");
+
+CodeMirror.defineMIME("text/x-rst", "rst");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/LICENSE b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/LICENSE
new file mode 100644
index 0000000000..ac09fc4035
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the Ubalo, Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/index.html
new file mode 100644
index 0000000000..6d33db192f
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/ruby/index.html
@@ -0,0 +1,171 @@
+
+
+
+ CodeMirror: Ruby mode
+
+
+
+
+
+
+
+
CodeMirror: Ruby mode
+
+
+
+
MIME types defined:text/x-ruby.
+
+
Development of the CodeMirror Ruby mode was kindly sponsored
+ by Ubalo, who hold
+ the license.
+
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/velocity/velocity.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/velocity/velocity.js
new file mode 100644
index 0000000000..0b80c75814
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/velocity/velocity.js
@@ -0,0 +1,146 @@
+CodeMirror.defineMode("velocity", function(config) {
+ function parseWords(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+
+ var indentUnit = config.indentUnit
+ var keywords = parseWords("#end #else #break #stop #[[ #]] " +
+ "#{end} #{else} #{break} #{stop}");
+ var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " +
+ "#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}");
+ var specials = parseWords("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent $velocityCount");
+ var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
+ var multiLineStrings =true;
+
+ function chain(stream, state, f) {
+ state.tokenize = f;
+ return f(stream, state);
+ }
+ function tokenBase(stream, state) {
+ var beforeParams = state.beforeParams;
+ state.beforeParams = false;
+ var ch = stream.next();
+ // start of string?
+ if ((ch == '"' || ch == "'") && state.inParams)
+ return chain(stream, state, tokenString(ch));
+ // is it one of the special signs []{}().,;? Seperator?
+ else if (/[\[\]{}\(\),;\.]/.test(ch)) {
+ if (ch == "(" && beforeParams) state.inParams = true;
+ else if (ch == ")") state.inParams = false;
+ return null;
+ }
+ // start of a number value?
+ else if (/\d/.test(ch)) {
+ stream.eatWhile(/[\w\.]/);
+ return "number";
+ }
+ // multi line comment?
+ else if (ch == "#" && stream.eat("*")) {
+ return chain(stream, state, tokenComment);
+ }
+ // unparsed content?
+ else if (ch == "#" && stream.match(/ *\[ *\[/)) {
+ return chain(stream, state, tokenUnparsed);
+ }
+ // single line comment?
+ else if (ch == "#" && stream.eat("#")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ // variable?
+ else if (ch == "$") {
+ stream.eatWhile(/[\w\d\$_\.{}]/);
+ // is it one of the specials?
+ if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
+ return "keyword";
+ }
+ else {
+ state.beforeParams = true;
+ return "builtin";
+ }
+ }
+ // is it a operator?
+ else if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return "operator";
+ }
+ else {
+ // get the whole word
+ stream.eatWhile(/[\w\$_{}]/);
+ var word = stream.current().toLowerCase();
+ // is it one of the listed keywords?
+ if (keywords && keywords.propertyIsEnumerable(word))
+ return "keyword";
+ // is it one of the listed functions?
+ if (functions && functions.propertyIsEnumerable(word) ||
+ stream.current().match(/^#[a-z0-9_]+ *$/i) && stream.peek()=="(") {
+ state.beforeParams = true;
+ return "keyword";
+ }
+ // default: just a "word"
+ return null;
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {
+ end = true;
+ break;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ if (end) state.tokenize = tokenBase;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "#" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ function tokenUnparsed(stream, state) {
+ var maybeEnd = 0, ch;
+ while (ch = stream.next()) {
+ if (ch == "#" && maybeEnd == 2) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ if (ch == "]")
+ maybeEnd++;
+ else if (ch != " ")
+ maybeEnd = 0;
+ }
+ return "meta";
+ }
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {
+ tokenize: tokenBase,
+ beforeParams: false,
+ inParams: false
+ };
+ },
+
+ token: function(stream, state) {
+ if (stream.eatSpace()) return null;
+ return state.tokenize(stream, state);
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/velocity", "velocity");
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/verilog/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/verilog/index.html
new file mode 100644
index 0000000000..775dd5374a
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/verilog/index.html
@@ -0,0 +1,210 @@
+
+
+
+ CodeMirror: Verilog mode
+
+
+
+
+
+
+
+
CodeMirror: Verilog mode
+
+
+
+
+
+
Simple mode that tries to handle Verilog-like languages as well as it
+ can. Takes one configuration parameters: keywords, an
+ object whose property names are the keywords in the language.
The XML mode supports two configuration parameters:
+
+
htmlMode (boolean)
+
This switches the mode to parse HTML instead of XML. This
+ means attributes do not have to be quoted, and some elements
+ (such as br) do not require a closing tag.
+
alignCDATA (boolean)
+
Setting this to true will force the opening tag of CDATA
+ blocks to not be indented.
+
+
+
MIME types defined:application/xml, text/html.
+
+
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xml/xml.js b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xml/xml.js
new file mode 100644
index 0000000000..060dad181b
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xml/xml.js
@@ -0,0 +1,326 @@
+CodeMirror.defineMode("xml", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var Kludges = parserConfig.htmlMode ? {
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+ 'track': true, 'wbr': true},
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+ 'th': true, 'tr': true},
+ contextGrabbers: {
+ 'dd': {'dd': true, 'dt': true},
+ 'dt': {'dd': true, 'dt': true},
+ 'li': {'li': true},
+ 'option': {'option': true, 'optgroup': true},
+ 'optgroup': {'optgroup': true},
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+ 'rp': {'rp': true, 'rt': true},
+ 'rt': {'rp': true, 'rt': true},
+ 'tbody': {'tbody': true, 'tfoot': true},
+ 'td': {'td': true, 'th': true},
+ 'tfoot': {'tbody': true},
+ 'th': {'td': true, 'th': true},
+ 'thead': {'tbody': true, 'tfoot': true},
+ 'tr': {'tr': true}
+ },
+ doNotIndent: {"pre": true},
+ allowUnquoted: true,
+ allowMissing: false
+ } : {
+ autoSelfClosers: {},
+ implicitlyClosed: {},
+ contextGrabbers: {},
+ doNotIndent: {},
+ allowUnquoted: false,
+ allowMissing: false
+ };
+ var alignCDATA = parserConfig.alignCDATA;
+
+ // Return variables for tokenizers
+ var tagName, type;
+
+ function inText(stream, state) {
+ function chain(parser) {
+ state.tokenize = parser;
+ return parser(stream, state);
+ }
+
+ var ch = stream.next();
+ if (ch == "<") {
+ if (stream.eat("!")) {
+ if (stream.eat("[")) {
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+ else return null;
+ }
+ else if (stream.match("--")) return chain(inBlock("comment", "-->"));
+ else if (stream.match("DOCTYPE", true, true)) {
+ stream.eatWhile(/[\w\._\-]/);
+ return chain(doctype(1));
+ }
+ else return null;
+ }
+ else if (stream.eat("?")) {
+ stream.eatWhile(/[\w\._\-]/);
+ state.tokenize = inBlock("meta", "?>");
+ return "meta";
+ }
+ else {
+ type = stream.eat("/") ? "closeTag" : "openTag";
+ stream.eatSpace();
+ tagName = "";
+ var c;
+ while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+ state.tokenize = inTag;
+ return "tag";
+ }
+ }
+ else if (ch == "&") {
+ var ok;
+ if (stream.eat("#")) {
+ if (stream.eat("x")) {
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+ } else {
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+ }
+ } else {
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
+ }
+ return ok ? "atom" : "error";
+ }
+ else {
+ stream.eatWhile(/[^&<]/);
+ return null;
+ }
+ }
+
+ function inTag(stream, state) {
+ var ch = stream.next();
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+ state.tokenize = inText;
+ type = ch == ">" ? "endTag" : "selfcloseTag";
+ return "tag";
+ }
+ else if (ch == "=") {
+ type = "equals";
+ return null;
+ }
+ else if (/[\'\"]/.test(ch)) {
+ state.tokenize = inAttribute(ch);
+ return state.tokenize(stream, state);
+ }
+ else {
+ stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
+ return "word";
+ }
+ }
+
+ function inAttribute(quote) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.next() == quote) {
+ state.tokenize = inTag;
+ break;
+ }
+ }
+ return "string";
+ };
+ }
+
+ function inBlock(style, terminator) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.match(terminator)) {
+ state.tokenize = inText;
+ break;
+ }
+ stream.next();
+ }
+ return style;
+ };
+ }
+ function doctype(depth) {
+ return function(stream, state) {
+ var ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == "<") {
+ state.tokenize = doctype(depth + 1);
+ return state.tokenize(stream, state);
+ } else if (ch == ">") {
+ if (depth == 1) {
+ state.tokenize = inText;
+ break;
+ } else {
+ state.tokenize = doctype(depth - 1);
+ return state.tokenize(stream, state);
+ }
+ }
+ }
+ return "meta";
+ };
+ }
+
+ var curState, setStyle;
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+
+ function pushContext(tagName, startOfLine) {
+ var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
+ curState.context = {
+ prev: curState.context,
+ tagName: tagName,
+ indent: curState.indented,
+ startOfLine: startOfLine,
+ noIndent: noIndent
+ };
+ }
+ function popContext() {
+ if (curState.context) curState.context = curState.context.prev;
+ }
+
+ function element(type) {
+ if (type == "openTag") {
+ curState.tagName = tagName;
+ return cont(attributes, endtag(curState.startOfLine));
+ } else if (type == "closeTag") {
+ var err = false;
+ if (curState.context) {
+ if (curState.context.tagName != tagName) {
+ if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) {
+ popContext();
+ }
+ err = !curState.context || curState.context.tagName != tagName;
+ }
+ } else {
+ err = true;
+ }
+ if (err) setStyle = "error";
+ return cont(endclosetag(err));
+ }
+ return cont();
+ }
+ function endtag(startOfLine) {
+ return function(type) {
+ if (type == "selfcloseTag" ||
+ (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase()))) {
+ maybePopContext(curState.tagName.toLowerCase());
+ return cont();
+ }
+ if (type == "endTag") {
+ maybePopContext(curState.tagName.toLowerCase());
+ pushContext(curState.tagName, startOfLine);
+ return cont();
+ }
+ return cont();
+ };
+ }
+ function endclosetag(err) {
+ return function(type) {
+ if (err) setStyle = "error";
+ if (type == "endTag") { popContext(); return cont(); }
+ setStyle = "error";
+ return cont(arguments.callee);
+ }
+ }
+ function maybePopContext(nextTagName) {
+ var parentTagName;
+ while (true) {
+ if (!curState.context) {
+ return;
+ }
+ parentTagName = curState.context.tagName.toLowerCase();
+ if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
+ !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+ return;
+ }
+ popContext();
+ }
+ }
+
+ function attributes(type) {
+ if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);}
+ if (type == "endTag" || type == "selfcloseTag") return pass();
+ setStyle = "error";
+ return cont(attributes);
+ }
+ function attribute(type) {
+ if (type == "equals") return cont(attvalue, attributes);
+ if (!Kludges.allowMissing) setStyle = "error";
+ return (type == "endTag" || type == "selfcloseTag") ? pass() : cont();
+ }
+ function attvalue(type) {
+ if (type == "string") return cont(attvaluemaybe);
+ if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
+ setStyle = "error";
+ return (type == "endTag" || type == "selfCloseTag") ? pass() : cont();
+ }
+ function attvaluemaybe(type) {
+ if (type == "string") return cont(attvaluemaybe);
+ else return pass();
+ }
+
+ return {
+ startState: function() {
+ return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ state.startOfLine = true;
+ state.indented = stream.indentation();
+ }
+ if (stream.eatSpace()) return null;
+
+ setStyle = type = tagName = null;
+ var style = state.tokenize(stream, state);
+ state.type = type;
+ if ((style || type) && style != "comment") {
+ curState = state;
+ while (true) {
+ var comb = state.cc.pop() || element;
+ if (comb(type || style)) break;
+ }
+ }
+ state.startOfLine = false;
+ return setStyle || style;
+ },
+
+ indent: function(state, textAfter, fullLine) {
+ var context = state.context;
+ if ((state.tokenize != inTag && state.tokenize != inText) ||
+ context && context.noIndent)
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+ if (alignCDATA && /
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xquery/index.html b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xquery/index.html
new file mode 100644
index 0000000000..82f00d2475
--- /dev/null
+++ b/src/Umbraco.Web.UI/umbraco_client/CodeMirror/js/mode/xquery/index.html
@@ -0,0 +1,222 @@
+
+
+
+
+ CodeMirror 2: JavaScript mode
+
+
+
+
+
+
+
+
+
CodeMirror 2: XQuery mode
+
+
+
+
+
+
+
+
MIME types defined:application/xquery.
+
+
Development of the CodeMirror XQuery mode was sponsored by
+ MarkLogic and developed by
+ Mike Brevoort.
+