1 define([
  2 	'aloha/core',
  3 	'aloha/ecma5shims',
  4 	'util/maps',
  5 	'util/html',
  6 	'util/dom',
  7 	'jquery'
  8 ], function (
  9 	Aloha,
 10 	$_,
 11 	Maps,
 12 	Html,
 13 	Dom,
 14 	jQuery
 15 ) {
 16 	"use strict";
 17 
 18 	/**
 19 	 *
 20 	 * @param obj
 21 	 * @param attr
 22 	 * @returns {Boolean} true
 23 	 */
 24 	function hasAttribute(obj, attr) {
 25 		var native_method = obj.hasAttribute;
 26 		if (native_method) {
 27 			return obj.hasAttribute(attr);
 28 		}
 29 		return (typeof obj.attributes[attr] !== 'undefined');
 30 	}
 31 
 32 	/**
 33 	 * Insert the node `node` after `preceding`.
 34 	 *
 35 	 * @param {Element} node
 36 	 * @param {Element} preceding
 37 	 * @return {Element}
 38 	 */
 39 	function insertAfter(node, preceding) {
 40 		var next = preceding.nextSibling,
 41 		    parent = preceding.parentNode;
 42 		if (next) {
 43 			parent.insertBefore(node, next);
 44 		} else {
 45 			parent.appendChild(node);
 46 		}
 47 		return node;
 48 	}
 49 
 50 	/**
 51 	 * Splits text node `node` at the given text index.
 52 	 *
 53  54 	 * Note that we cannot use splitText() because it is bugridden in IE 9.
 55 	 *
 56 	 * Borrowed from rangy.
 57 	 *
 58 	 * @param {Element} node
 59 	 * @param {number} index
 60 	 * @return {Element}
 61 	 */
 62 	function splitText(node, index) {
 63 		var newNode = node.cloneNode(false);
 64 		newNode.deleteData(0, index);
 65 		node.deleteData(index, node.length - index);
 66 		insertAfter(newNode, node);
 67 		return newNode;
 68 	}
 69 
 70 	var htmlNamespace = "http://www.w3.org/1999/xhtml";
 71 
 72 	var cssStylingFlag = false;
 73 
 74 	// This is bad :(
 75 	var globalRange = null;
 76 
 77 	// Commands are stored in a dictionary where we call their actions and such
 78 	var commands = {};
 79 
 80 	///////////////////////////////////////////////////////////////////////////////
 81 	////////////////////////////// Utility functions //////////////////////////////
 82 	///////////////////////////////////////////////////////////////////////////////
 83 	//@{
 84 
 85 	// Opera 11 puts HTML elements in the null namespace, it seems.
 86 	function isHtmlNamespace(ns) {
 87 		return ns === null || !ns || ns === htmlNamespace;
 88 	}
 89 
 90 	// "An HTML element is an Element whose namespace is the HTML namespace."
 91 	//
 92 	// I allow an extra argument to more easily check whether something is a
 93 	// particular HTML element, like isNamedHtmlElement(node, 'OL').  It accepts arrays
 94 	// too, like isHtmlElementInArray(node, ["OL", "UL"]) to check if it's an ol or ul.
 95 	// TODO This function was prominent during profiling. Remove it
 96 	//      and replace with calls to isAnyHtmlElement, isNamedHtmlElement
 97 	//      and is isMappedHtmlElement.
 98 	function isHtmlElement_obsolete(node, tags) {
 99 		if (typeof tags == "string") {
100 			tags = [tags];
101 		}
102 		if (typeof tags == "object") {
103 			tags = $_(tags).map(function (tag) {
104 				return tag.toUpperCase();
105 			});
106 		}
107 		return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) && (typeof tags == "undefined" || $_(tags).indexOf(node.tagName) != -1);
108 	}
109 
110 	function isAnyHtmlElement(node) {
111 		return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI);
112 	}
113 
114 	// name should be uppercase
115 	function isNamedHtmlElement(node, name) {
116 		return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI)
117 		// This function is passed in a mix of upper and lower case names
118 			&& name.toUpperCase() === node.nodeName;
119 	}
120 
121 	// TODO remove when isHtmlElementInArray is removed
122 	function arrayContainsInsensitive(array, str) {
123 		var i, len;
124 		str = str.toUpperCase();
125 		for (i = 0, len = array.length; i < len; i++) {
126 			if (array[i].toUpperCase() === str) {
127 				return true;
128 			}
129 		}
130 		return false;
131 	}
132 	// TODO replace calls to this function with calls to isMappedHtmlElement()
133 	function isHtmlElementInArray(node, array) {
134 		return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI)
135 		// This function is passed in a mix of upper and lower case names
136 			&& arrayContainsInsensitive(array, node.nodeName);
137 	}
138 
139 	// map must have all-uppercase keys
140 	function isMappedHtmlElement(node, map) {
141 		return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) && map[node.nodeName];
142 	}
143 
144 	/**
145 	 * Method to count the number of styles in the given style
146 	 */
147 	function getStyleLength(node) {
148 		var s;
149 		var styleLength = 0;
150 
151 		if (!node) {
152 			return 0;
153 		}
154 
155 		if (!node.style) {
156 			return 0;
157 		}
158 
159 		// some browsers support .length on styles
160 		if (typeof node.style.length !== 'undefined') {
161 			return node.style.length;
162 		}
163 
164 		/*jslint forin: true*/ //not sure whether node.style.hasOwnProperty is valid
165 		for (s in node.style) {
166 			if (node.style[s] && node.style[s] !== 0 && node.style[s] !== 'false') {
167 				styleLength++;
168 			}
169 		}
170 		/*jslint forin: false*/
171 
172 		return styleLength;
173 	}
174 
175 	function toArray(obj) {
176 		if (!obj) {
177 			return null;
178 		}
179 		var array = [],
180 			i,
181 		    l = obj.length;
182 		// iterate backwards ensuring that length is an UInt32
183 		i = l >>> 0;
184 		while (i--) {
185 			array[i] = obj[i];
186 		}
187 		return array;
188 	}
189 
190 	function nextNodeDescendants(node) {
191 		while (node && !node.nextSibling) {
192 			node = node.parentNode;
193 		}
194 		if (!node) {
195 			return null;
196 		}
197 		return node.nextSibling;
198 	}
199 
200 	function nextNode(node) {
201 		if (node.hasChildNodes()) {
202 			return node.firstChild;
203 		}
204 		return nextNodeDescendants(node);
205 	}
206 
207 	function previousNode(node) {
208 		if (node.previousSibling) {
209 			node = node.previousSibling;
210 			while (node.hasChildNodes()) {
211 				node = node.lastChild;
212 			}
213 			return node;
214 		}
215 		if (node.parentNode && node.parentNode.nodeType == $_.Node.ELEMENT_NODE) {
216 			return node.parentNode;
217 		}
218 		return null;
219 	}
220 
221 	/**
222 	 * Returns true if ancestor is an ancestor of descendant, false otherwise.
223 	 */
224 	function isAncestor(ancestor, descendant) {
225 		return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY);
226 	}
227 
228 	/**
229 	 * Returns true if ancestor is an ancestor of or equal to descendant, false
230 	 * otherwise.
231 	 */
232 	function isAncestorContainer(ancestor, descendant) {
233 		return (ancestor || descendant) && (ancestor == descendant || isAncestor(ancestor, descendant));
234 	}
235 
236 	/**
237 	 * Returns true if descendant is a descendant of ancestor, false otherwise.
238 	 */
239 	function isDescendant(descendant, ancestor) {
240 		return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY);
241 	}
242 
243 	/**
244 	 * Returns true if node1 is before node2 in tree order, false otherwise.
245 	 */
246 	function isBefore(node1, node2) {
247 		return Boolean($_.compareDocumentPosition(node1, node2) & $_.Node.DOCUMENT_POSITION_FOLLOWING);
248 	}
249 
250 	/**
251 	 * Returns true if node1 is after node2 in tree order, false otherwise.
252 	 */
253 	function isAfter(node1, node2) {
254 		return Boolean($_.compareDocumentPosition(node1, node2) & $_.Node.DOCUMENT_POSITION_PRECEDING);
255 	}
256 
257 	function getAncestors(node) {
258 		var ancestors = [];
259 260 		while (node.parentNode) {
261 			ancestors.unshift(node.parentNode);
262 			node = node.parentNode;
263 		}
264 		return ancestors;
265 	}
266 
267 	function getDescendants(node) {
268 		var descendants = [];
269 		var stop = nextNodeDescendants(node);
270 		while (null != (node = nextNode(node)) && node != stop) {
271 			descendants.push(node);
272 		}
273 		return descendants;
274 	}
275 
276 	function convertProperty(property) {
277 		// Special-case for now
278 		var map = {
279 			"fontFamily": "font-family",
280 			"fontSize": "font-size",
281 			"fontStyle": "font-style",
282 			"fontWeight": "font-weight",
283 			"textDecoration": "text-decoration"
284 		};
285 		if (typeof map[property] != "undefined") {
286 			return map[property];
287 		}
288 
289 		return property;
290 	}
291 
292 	// Return the <font size=X> value for the given CSS size, or undefined if there
293 	// is none.
294 	function cssSizeToLegacy(cssVal) {
295 		return {
296 			"xx-small": 1,
297 			"small": 2,
298 			"medium": 3,
299 			"large": 4,
300 			"x-large": 5,
301 			"xx-large": 6,
302 			"xxx-large": 7
303 		}[cssVal];
304 	}
305 
306 	// Return the CSS size given a legacy size.
307 	function legacySizeToCss(legacyVal) {
308 		return {
309 			1: "xx-small",
310 			2: "small",
311 			3: "medium",
312 			4: "large",
313 			5: "x-large",
314 			6: "xx-large",
315 			7: "xxx-large"
316 		}[legacyVal];
317 	}
318 
319 	// "the directionality" from HTML.  I don't bother caring about non-HTML
320 	// elements.
321 	//
322 	// "The directionality of an element is either 'ltr' or 'rtl', and is
323 	// determined as per the first appropriate set of steps from the following
324 	// list:"
325 	function getDirectionality(element) {
326 		// "If the element's dir attribute is in the ltr state
327 		//     The directionality of the element is 'ltr'."
328 		if (element.dir == "ltr") {
329 			return "ltr";
330 		}
331 
332 		// "If the element's dir attribute is in the rtl state
333 		//     The directionality of the element is 'rtl'."
334 		if (element.dir == "rtl") {
335 			return "rtl";
336 		}
337 
338 		// "If the element's dir attribute is in the auto state
339 		// "If the element is a bdi element and the dir attribute is not in a
340 		// defined state (i.e. it is not present or has an invalid value)
341 		//     [lots of complicated stuff]
342 		//
343 		// Skip this, since no browser implements it anyway.
344 
345 		// "If the element is a root element and the dir attribute is not in a
346 		// defined state (i.e. it is not present or has an invalid value)
347 		//     The directionality of the element is 'ltr'."
348 		if (!isAnyHtmlElement(element.parentNode)) {
349 			return "ltr";
350 		}
351 
352 		// "If the element has a parent element and the dir attribute is not in a
353 		// defined state (i.e. it is not present or has an invalid value)
354 		//     The directionality of the element is the same as the element's
355 		//     parent element's directionality."
356 		return getDirectionality(element.parentNode);
357 	}
358 
359 	//@}
360 
361 	///////////////////////////////////////////////////////////////////////////////
362 	///////////////////////////// DOM Range functions /////////////////////////////
363 	///////////////////////////////////////////////////////////////////////////////
364 	//@{
365 
366 	// "The length of a Node node is the following, depending on node:
367 	//
368 	// ProcessingInstruction
369 	// DocumentType
370 	//   Always 0.
371 	// Text
372 	// Comment
373 	//   node's length.
374 	// Any other node
375 	//   node's childNodes's length."
376 	function getNodeLength(node) {
377 		switch (node.nodeType) {
378 		case $_.Node.PROCESSING_INSTRUCTION_NODE:
379 		case $_.Node.DOCUMENT_TYPE_NODE:
380 			return 0;
381 
382 		case $_.Node.TEXT_NODE:
383 		case $_.Node.COMMENT_NODE:
384 			return node.length;
385 
386 		default:
387 			return node.childNodes.length;
388 		}
389 	}
390 
391 	/**
392 	 * The position of two boundary points relative to one another, as defined by
393 	 * DOM Range.
394 	 */
395 	function getPosition(nodeA, offsetA, nodeB, offsetB) {
396 		// "If node A is the same as node B, return equal if offset A equals offset
397 		// B, before if offset A is less than offset B, and after if offset A is
398 		// greater than offset B."
399 		if (nodeA == nodeB) {
400 			if (offsetA == offsetB) {
401 				return "equal";
402 			}
403 			if (offsetA < offsetB) {
404 				return "before";
405 			}
406 			if (offsetA > offsetB) {
407 				return "after";
408 			}
409 		}
410 
411 		var documentPosition = $_.compareDocumentPosition(nodeB, nodeA);
412 		// "If node A is after node B in tree order, compute the position of (node
413 		// B, offset B) relative to (node A, offset A). If it is before, return
414 		// after. If it is after, return before."
415 		if (documentPosition & $_.Node.DOCUMENT_POSITION_FOLLOWING) {
416 			var pos = getPosition(nodeB, offsetB, nodeA, offsetA);
417 			if (pos == "before") {
418 				return "after";
419 			}
420 			if (pos == "after") {
421 				return "before";
422 			}
423 		}
424 
425 		// "If node A is an ancestor of node B:"
426 		if (documentPosition & $_.Node.DOCUMENT_POSITION_CONTAINS) {
427 			// "Let child equal node B."
428 			var child = nodeB;
429 
430 			// "While child is not a child of node A, set child to its parent."
431 			while (child.parentNode != nodeA) {
432 				child = child.parentNode;
433 			}
434 
435 			// "If the index of child is less than offset A, return after."
436 			if (Dom.getIndexInParent(child) < offsetA) {
437 				return "after";
438 			}
439 		}
440 
441 		// "Return before."
442 		return "before";
443 	}
444 
445 	/**
446 	 * Returns the furthest ancestor of a Node as defined by DOM Range.
447 	 */
448 	function getFurthestAncestor(node) {
449 		var root = node;
450 		while (root.parentNode != null) {
451 			root = root.parentNode;
452 		}
453 		return root;
454 	}
455 
456 	/**
457 	 * "contained" as defined by DOM Range: "A Node node is contained in a range
458 	 * range if node's furthest ancestor is the same as range's root, and (node, 0)
459 	 * is after range's start, and (node, length of node) is before range's end."
460 	 */
461 	function isContained(node, range) {
462 		var pos1 = getPosition(node, 0, range.startContainer, range.startOffset);
463 		if (pos1 !== "after") {
464 			return false;
465 		}
466 		var pos2 = getPosition(node, getNodeLength(node), range.endContainer, range.endOffset);
467 		if (pos2 !== "before") {
468 			return false;
469 		}
470 		return getFurthestAncestor(node) == getFurthestAncestor(range.startContainer);
471 	}
472 
473 	/**
474 	 * Return all nodes contained in range that the provided function returns true
475 	 * for, omitting any with an ancestor already being returned.
476 	 */
477 	function getContainedNodes(range, condition) {
478 		if (typeof condition == "undefined") {
479 			condition = function () {
480 				return true;
481 			};
482 		}
483 		var node = range.startContainer;
484 		if (node.hasChildNodes() && range.startOffset < node.childNodes.length) {
485 			// A child is contained
486 			node = node.childNodes[range.startOffset];
487 		} else if (range.startOffset == getNodeLength(node)) {
488 			// No descendant can be contained
489 			node = nextNodeDescendants(node);
490 		} else {
491 			// No children; this node at least can't be contained
492 			node = nextNode(node);
493 		}
494 
495 		var stop = range.endContainer;
496 		if (stop.hasChildNodes() && range.endOffset < stop.childNodes.length) {
497 			// The node after the last contained node is a child
498 			stop = stop.childNodes[range.endOffset];
499 		} else {
500 			// This node and/or some of its children might be contained
501 			stop = nextNodeDescendants(stop);
502 		}
503 
504 		var nodeList = [];
505 		while (isBefore(node, stop)) {
506 			if (isContained(node, range) && condition(node)) {
507 				nodeList.push(node);
508 				node = nextNodeDescendants(node);
509 				continue;
510 			}
511 			node = nextNode(node);
512 		}
513 		return nodeList;
514 	}
515 
516 	/**
517 	 * As above, but includes nodes with an ancestor that's already been returned.
518 	 */
519 	function getAllContainedNodes(range, condition) {
520 		if (typeof condition == "undefined") {
521 			condition = function () {
522 				return true;
523 			};
524 		}
525 		var node = range.startContainer;
526 		if (node.hasChildNodes() && range.startOffset < node.childNodes.length) {
527 			// A child is contained
528 			node = node.childNodes[range.startOffset];
529 		} else if (range.startOffset == getNodeLength(node)) {
530 			// No descendant can be contained
531 			node = nextNodeDescendants(node);
532 		} else {
533 			// No children; this node at least can't be contained
534 			node = nextNode(node);
535 		}
536 
537 		var stop = range.endContainer;
538 		if (stop.hasChildNodes() && range.endOffset < stop.childNodes.length) {
539 			// The node after the last contained node is a child
540 			stop = stop.childNodes[range.endOffset];
541 		} else {
542 			// This node and/or some of its children might be contained
543 			stop = nextNodeDescendants(stop);
544 		}
545 
546 		var nodeList = [];
547 		while (isBefore(node, stop)) {
548 			if (isContained(node, range) && condition(node)) {
549 				nodeList.push(node);
550 			}
551 			node = nextNode(node);
552 		}
553 		return nodeList;
554 	}
555 
556 	// Returns either null, or something of the form rgb(x, y, z), or something of
557 	// the form rgb(x, y, z, w) with w != 0.
558 	function normalizeColor(color) {
559 		if (color.toLowerCase() == "currentcolor") {
560 			return null;
561 		}
562 
563 		var outerSpan = document.createElement("span");
564 		document.body.appendChild(outerSpan);
565 		outerSpan.style.color = "black";
566 
567 		var innerSpan = document.createElement("span");
568 		outerSpan.appendChild(innerSpan);
569 		innerSpan.style.color = color;
570 		color = $_.getComputedStyle(innerSpan).color;
571 
572 		if (color == "rgb(0, 0, 0)") {
573 			// Maybe it's really black, maybe it's invalid.
574 			outerSpan.color = "white";
575 			color = $_.getComputedStyle(innerSpan).color;
576 			if (color != "rgb(0, 0, 0)") {
577 				return null;
578 			}
579 		}
580 
581 		document.body.removeChild(outerSpan);
582 
583 		// I rely on the fact that browsers generally provide consistent syntax for
584 		// getComputedStyle(), although it's not standardized.  There are only two
585 		// exceptions I found:
586 		if (/^rgba\([0-9]+, [0-9]+, [0-9]+, 1\)$/.test(color)) {
587 			// IE10PP2 seems to do this sometimes.
588 			return color.replace("rgba", "rgb").replace(", 1)", ")");
589 		}
590 		if (color == "transparent") {
591 			// IE10PP2, Firefox 7.0a2, and Opera 11.50 all return "transparent" if
592 			// the specified value is "transparent".
593 			return "rgba(0, 0, 0, 0)";
594 		}
595 		return color;
596 597 	}
598 
599 	// Returns either null, or something of the form #xxxxxx, or the color itself
600 	// if it's a valid keyword.
601 	function parseSimpleColor(color) {
602 		color = color.toLowerCase();
603 		if ($_(["aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "grey", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen"]).indexOf(color) != -1) {
604 			return color;
605 		}
606 
607 		color = normalizeColor(color);
608 		var matches = /^rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)$/.exec(color);
609 		if (matches) {
610 			return "#" + parseInt(matches[1], 10).toString(16).replace(/^.$/, "0$&") + parseInt(matches[2], 10).toString(16).replace(/^.$/, "0$&") + parseInt(matches[3], 10).toString(16).replace(/^.$/, "0$&");
611 		} else if (/^#[abcdef0123456789]+$/i.exec(color)) {
612 			// return hexadecimal color values (as returned by IE 7/8)
613 			return color;
614 		}
615 		return null;
616 	}
617 
618 	//@}
619 
620 	//////////////////////////////////////////////////////////////////////////////
621 	/////////////////////////// Edit command functions ///////////////////////////
622 	//////////////////////////////////////////////////////////////////////////////
623 
624 	/////////////////////////////////////////////////
625 	///// Methods of the HTMLDocument interface /////
626 	/////////////////////////////////////////////////
627 	//@{
628 
629 	var getStateOverride,
630 	    setStateOverride,
631 	    resetOverrides,
632 	    unsetStateOverride,
633 	    getValueOverride,
634 	    setValueOverride,
635 	    unsetValueOverride;
636 
637 	var executionStackDepth = 0;
638 
639 	// Helper function for fontSize's action plus queryOutputHelper.  It's just the
640 	// middle of fontSize's action, ripped out into its own function.
641 	function normalizeFontSize(value) {
642 		// "Strip leading and trailing whitespace from value."
643 		//
644 		// Cheap hack, not following the actual algorithm.
645 		value = $_(value).trim();
646 
647 		// "If value is a valid floating point number, or would be a valid
648 		// floating point number if a single leading "+" character were
649 		// stripped:"
650 		if (/^[\-+]?[0-9]+(\.[0-9]+)?([eE][\-+]?[0-9]+)?$/.test(value)) {
651 			var mode;
652 
653 			// "If the first character of value is "+", delete the character
654 			// and let mode be "relative-plus"."
655 			if (value[0] == "+") {
656 				value = value.slice(1);
657 				mode = "relative-plus";
658 				// "Otherwise, if the first character of value is "-", delete the
659 				// character and let mode be "relative-minus"."
660 			} else if (value[0] == "-") {
661 				value = value.slice(1);
662 				mode = "relative-minus";
663 				// "Otherwise, let mode be "absolute"."
664 			} else {
665 				mode = "absolute";
666 			}
667 
668 			// "Apply the rules for parsing non-negative integers to value, and
669 			// let number be the result."
670 			//
671 			// Another cheap hack.
672 			var num = parseInt(value, 10);
673 
674 			// "If mode is "relative-plus", add three to number."
675 			if (mode == "relative-plus") {
676 				num += 3;
677 			}
678 
679 			// "If mode is "relative-minus", negate number, then add three to
680 			// it."
681 			if (mode == "relative-minus") {
682 				num = 3 - num;
683 			}
684 
685 			// "If number is less than one, let number equal 1."
686 			if (num < 1) {
687 				num = 1;
688 			}
689 
690 			// "If number is greater than seven, let number equal 7."
691 			if (num > 7) {
692 				num = 7;
693 			}
694 
695 			// "Set value to the string here corresponding to number:" [table
696 			// omitted]
697 			value = {
698 				1: "xx-small",
699 				2: "small",
700 				3: "medium",
701 				4: "large",
702 				5: "x-large",
703 				6: "xx-large",
704 				7: "xxx-large"
705 			}[num];
706 		}
707 
708 		return value;
709 	}
710 
711 	function getLegacyFontSize(size) {
712 		// For convenience in other places in my code, I handle all sizes, not just
713 		// pixel sizes as the spec says.  This means pixel sizes have to be passed
714 		// in suffixed with "px", not as plain numbers.
715 		size = normalizeFontSize(size);
716 
717 		if (jQuery.inArray(size, ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) == -1 && !/^[0-9]+(\.[0-9]+)?(cm|mm|in|pt|pc|px)$/.test(size)) {
718 			// There is no sensible legacy size for things like "2em".
719 			return null;
720 		}
721 
722 		var font = document.createElement("font");
723 		document.body.appendChild(font);
724 		if (size == "xxx-large") {
725 			font.size = 7;
726 		} else {
727 			font.style.fontSize = size;
728 		}
729 		var pixelSize = parseInt($_.getComputedStyle(font).fontSize, 10);
730 		document.body.removeChild(font);
731 
732 		// "Let returned size be 1."
733 		var returnedSize = 1;
734 
735 		// "While returned size is less than 7:"
736 		while (returnedSize < 7) {
737 			// "Let lower bound be the resolved value of "font-size" in pixels
738 			// of a font element whose size attribute is set to returned size."
739 			font = document.createElement("font");
740 			font.size = returnedSize;
741 			document.body.appendChild(font);
742 			var lowerBound = parseInt($_.getComputedStyle(font).fontSize, 10);
743 
744 			// "Let upper bound be the resolved value of "font-size" in pixels
745 			// of a font element whose size attribute is set to one plus
746 			// returned size."
747 			font.size = 1 + returnedSize;
748 			var upperBound = parseInt($_.getComputedStyle(font).fontSize, 10);
749 			document.body.removeChild(font);
750 
751 			// "Let average be the average of upper bound and lower bound."
752 			var average = (upperBound + lowerBound) / 2;
753 
754 			// "If pixel size is less than average, return the one-element
755 			// string consisting of the digit returned size."
756 			if (pixelSize < average) {
757 				return String(returnedSize);
758 			}
759 
760 			// "Add one to returned size."
761 			returnedSize++;
762 		}
763 
764 		// "Return "7"."
765 		return "7";
766 	}
767 
768 	// Helper function for common behavior.
769 	function editCommandMethod(command, prop, range, callback) {
770 		var ret;
771 
772 		// Set up our global range magic, but only if we're the outermost function
773 		if (executionStackDepth === 0) {
774 			globalRange = range;
775 		}
776 
777 		executionStackDepth++;
778 		try {
779 			ret = callback();
780 		} catch (e) {
781 			executionStackDepth--;
782 			throw e;
783 		}
784 		executionStackDepth--;
785 		return ret;
786 	}
787 
788 	function myQueryCommandEnabled(command, range) {
789 		// "All of these methods must treat their command argument ASCII
790 		// case-insensitively."
791 		command = command.toLowerCase();
792 
793 		// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
794 		return editCommandMethod(command, "action", range, (function (command) {
795 			return function () {
796 				// "Among commands defined in this specification, those listed in
797 				// Miscellaneous commands are always enabled. The other commands defined
798 				// here are enabled if the active range is not null, and disabled
799 				// otherwise."
800 				return jQuery.inArray(command, ["copy", "cut", "paste", "selectall", "stylewithcss", "usecss"]) != -1 || range !== null;
801 			};
802 		}(command)));
803 	}
804 
805 	function setActiveRange(range) {
806 		var rangeObject = new window.GENTICS.Utils.RangeObject();
807 
808 		rangeObject.startContainer = range.startContainer;
809 		rangeObject.startOffset = range.startOffset;
810 		rangeObject.endContainer = range.endContainer;
811 		rangeObject.endOffset = range.endOffset;
812 
813 		rangeObject.select();
814 	}
815 
816 	function myExecCommand(commandArg, showUiArg, valueArg, range) {
817 		// "All of these methods must treat their command argument ASCII
818 		// case-insensitively."
819 		var command = commandArg.toLowerCase();
820 		var showUi = showUiArg;
821 		var value = valueArg;
822 
823 		// "If only one argument was provided, let show UI be false."
824 		//
825 		// If range was passed, I can't actually detect how many args were passed
826 		// . . .
827 		if (arguments.length == 1 || (arguments.length >= 4 && typeof showUi == "undefined")) {
828 			showUi = false;
829 		}
830 
831 		// "If only one or two arguments were provided, let value be the empty
832 		// string."
833 		if (arguments.length <= 2 || (arguments.length >= 4 && typeof value == "undefined")) {
834 			value = "";
835 		}
836 
837 		// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
838 		//
839 		// "If command has no action, raise an INVALID_ACCESS_ERR exception."
840 		return editCommandMethod(command, "action", range, (function (command, showUi, value) {
841 			return function () {
842 				// "If command is not enabled, return false."
843 				if (!myQueryCommandEnabled(command)) {
844 					return false;
845 				}
846 
847 				// "Take the action for command, passing value to the instructions as an
848 				// argument."
849 				commands[command].action(value, range);
850 
851 				// always fix the range after the command is complete
852 				setActiveRange(range);
853 
854 				// "Return true."
855 				return true;
856 			};
857 		}(command, showUi, value)));
858 	}
859 
860 	function myQueryCommandIndeterm(command, range) {
861 		// "All of these methods must treat their command argument ASCII
862 		// case-insensitively."
863 		command = command.toLowerCase();
864 
865 		// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
866 		//
867 		// "If command has no indeterminacy, raise an INVALID_ACCESS_ERR
868 		// exception."
869 		return editCommandMethod(command, "indeterm", range, (function (command) {
870 			return function () {
871 				// "If command is not enabled, return false."
872 				if (!myQueryCommandEnabled(command, range)) {
873 					return false;
874 				}
875 
876 				// "Return true if command is indeterminate, otherwise false."
877 				return commands[command].indeterm(range);
878 			};
879 		}(command)));
880 	}
881 
882 	function myQueryCommandState(command, range) {
883 		// "All of these methods must treat their command argument ASCII
884 		// case-insensitively."
885 		command = command.toLowerCase();
886 
887 		// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
888 		//
889 		// "If command has no state, raise an INVALID_ACCESS_ERR exception."
890 		return editCommandMethod(command, "state", range, (function (command) {
891 			return function () {
892 				// "If command is not enabled, return false."
893 				if (!myQueryCommandEnabled(command, range)) {
894 					return false;
895 				}
896 
897 				// "If the state override for command is set, return it."
898 				if (typeof getStateOverride(command, range) != "undefined") {
899 					return getStateOverride(command, range);
900 				}
901 
902 				// "Return true if command's state is true, otherwise false."
903 				return commands[command].state(range);
904 			};
905 		}(command)));
906 	}
907 
908 	// "When the queryCommandSupported(command) method on the HTMLDocument
909 	// interface is invoked, the user agent must return true if command is
910 	// supported, and false otherwise."
911 	function myQueryCommandSupported(command) {
912 		// "All of these methods must treat their command argument ASCII
913 		// case-insensitively."
914 		command = command.toLowerCase();
915 
916 		return commands.hasOwnProperty(command);
917 	}
918 
919 	function myQueryCommandValue(command, range) {
920 		// "All of these methods must treat their command argument ASCII
921 		// case-insensitively."
922 		command = command.toLowerCase();
923 
924 		return editCommandMethod(command, "value", range, function () {
925 			// "If command is not supported or has no value, return the empty string."
926 			if (!commands.hasOwnProperty(command) || !commands[command].hasOwnProperty("value")) {
927 				return "";
928 			}
929 
930 			// "If command is "fontSize" and its value override is set, convert the
931 			// value override to an integer number of pixels and return the legacy
932 			// font size for the result."
933 			if (command == "fontsize" && getValueOverride("fontsize", range) !== undefined) {
934 				return getLegacyFontSize(getValueOverride("fontsize", range));
935 			}
936 
937 			// "If the value override for command is set, return it."
938 			if (typeof getValueOverride(command, range) != "undefined") {
939 				return getValueOverride(command, range);
940 			}
941 
942 			// "Return command's value."
943 			return commands[command].value(range);
944 		});
945 	}
946 	//@}
947 
948 	//////////////////////////////
949 	///// Common definitions /////
950 	//////////////////////////////
951 	//@{
952 
953 	// "A prohibited paragraph child name is "address", "article", "aside",
954 	// "blockquote", "caption", "center", "col", "colgroup", "dd", "details",
955 	// "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer",
956 	// "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li",
957 	// "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section",
958 	// "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", or
959 	// "xmp"."
960 	var prohibitedParagraphChildNamesMap = {
961 		"ADDRESS": true,
962 		"ARTICLE": true,
963 		"ASIDE": true,
964 		"BLOCKQUOTE": true,
965 		"CAPTION": true,
966 		"CENTER": true,
967 		"COL": true,
968 		"COLGROUP": true,
969 		"DD": true,
970 		"DETAILS": true,
971 		"DIR": true,
972 		"DIV": true,
973 		"DL": true,
974 		"DT": true,
975 		"FIELDSET": true,
976 		"FIGCAPTION": true,
977 		"FIGURE": true,
978 		"FOOTER": true,
979 		"FORM": true,
980 981 		"H1": true,
982 		"H2": true,
983 		"H3": true,
984 		"H4": true,
985 		"H5": true,
986 		"H6": true,
987 		"HEADER": true,
988 		"HGROUP": true,
989 		"HR": true,
990 		"LI": true,
991 		"LISTING": true,
992 		"MENU": true,
993 		"NAV": true,
994 		"OL": true,
995 		"P": true,
996 		"PLAINTEXT": true,
997 		"PRE": true,
998 		"SECTION": true,
999 		"SUMMARY": true,
1000 		"TABLE": true,
1001 		"TBODY": true,
1002 		"TD": true,
1003 		"TFOOT": true,
1004 		"TH": true,
1005 		"THEAD": true,
1006 		"TR": true,
1007 		"UL": true,
1008 		"XMP": true
1009 	};
1010 
1011 	// "A prohibited paragraph child is an HTML element whose local name is a
1012 	// prohibited paragraph child name."
1013 	function isProhibitedParagraphChild(node) {
1014 		return isMappedHtmlElement(node, prohibitedParagraphChildNamesMap);
1015 	}
1016 
1017 	var nonBlockDisplayValuesMap = {
1018 		"inline": true,
1019 		"inline-block": true,
1020 		"inline-table": true,
1021 		"none": true
1022 	};
1023 
1024 	// "A block node is either an Element whose "display" property does not have
1025 	// resolved value "inline" or "inline-block" or "inline-table" or "none", or a
1026 	// Document, or a DocumentFragment."
1027 	function isBlockNode(node) {
1028 		return node && ((node.nodeType == $_.Node.ELEMENT_NODE && !nonBlockDisplayValuesMap[$_.getComputedStyle(node).display]) || node.nodeType == $_.Node.DOCUMENT_NODE || node.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE);
1029 	}
1030 
1031 	// "An inline node is a node that is not a block node."
1032 	function isInlineNode(node) {
1033 		return node && !isBlockNode(node);
1034 	}
1035 
1036 	// "An editing host is a node that is either an Element with a contenteditable
1037 	// attribute set to the true state, or the Element child of a Document whose
1038 	// designMode is enabled."
1039 	function isEditingHost(node) {
1040 		return node && node.nodeType == $_.Node.ELEMENT_NODE && (node.contentEditable == "true" || (node.parentNode && node.parentNode.nodeType == $_.Node.DOCUMENT_NODE && node.parentNode.designMode == "on"));
1041 	}
1042 
1043 	// "Something is editable if it is a node which is not an editing host, does
1044 	// not have a contenteditable attribute set to the false state, and whose
1045 	// parent is an editing host or editable."
1046 	function isEditable(node) {
1047 		// This is slightly a lie, because we're excluding non-HTML elements with
1048 		// contentEditable attributes.
1049 		return node && !isEditingHost(node) && (node.nodeType != $_.Node.ELEMENT_NODE || node.contentEditable != "false" || jQuery(node).hasClass('aloha-table-wrapper')) && (isEditingHost(node.parentNode) || isEditable(node.parentNode));
1050 	}
1051 
1052 	// Helper function, not defined in the spec
1053 	function hasEditableDescendants(node) {
1054 		var i;
1055 		for (i = 0; i < node.childNodes.length; i++) {
1056 			if (isEditable(node.childNodes[i]) || hasEditableDescendants(node.childNodes[i])) {
1057 				return true;
1058 			}
1059 		}
1060 		return false;
1061 	}
1062 
1063 	// "The editing host of node is null if node is neither editable nor an editing
1064 	// host; node itself, if node is an editing host; or the nearest ancestor of
1065 	// node that is an editing host, if node is editable."
1066 	function getEditingHostOf(node) {
1067 		if (isEditingHost(node)) {
1068 			return node;
1069 		}
1070 		if (isEditable(node)) {
1071 			var ancestor = node.parentNode;
1072 			while (!isEditingHost(ancestor)) {
1073 				ancestor = ancestor.parentNode;
1074 			}
1075 			return ancestor;
1076 		}
1077 		return null;
1078 	}
1079 
1080 	// "Two nodes are in the same editing host if the editing host of the first is
1081 	// non-null and the same as the editing host of the second."
1082 	function inSameEditingHost(node1, node2) {
1083 		return getEditingHostOf(node1) && getEditingHostOf(node1) == getEditingHostOf(node2);
1084 	}
1085 
1086 	// "A collapsed line break is a br that begins a line box which has nothing
1087 	// else in it, and therefore has zero height."
1088 	function isCollapsedLineBreak(br) {
1089 		if (!isNamedHtmlElement(br, 'br')) {
1090 			return false;
1091 		}
1092 
1093 		// Add a zwsp after it and see if that changes the height of the nearest
1094 		// non-inline parent.  Note: this is not actually reliable, because the
1095 		// parent might have a fixed height or something.
1096 		var ref = br.parentNode;
1097 		while ($_.getComputedStyle(ref).display == "inline") {
1098 			ref = ref.parentNode;
1099 		}
1100 
1101 		var origStyle = {
1102 			height: ref.style.height,
1103 			maxHeight: ref.style.maxHeight,
1104 			minHeight: ref.style.minHeight
1105 		};
1106 
1107 		ref.style.height = 'auto';
1108 		ref.style.maxHeight = 'none';
1109 		if (!(jQuery.browser.msie && jQuery.browser.version < 8)) {
1110 			ref.style.minHeight = '0';
1111 		}
1112 		var space = document.createTextNode('\u200b');
1113 		var origHeight = ref.offsetHeight;
1114 		if (origHeight == 0) {
1115 			throw 'isCollapsedLineBreak: original height is zero, bug?';
1116 		}
1117 		br.parentNode.insertBefore(space, br.nextSibling);
1118 		var finalHeight = ref.offsetHeight;
1119 		space.parentNode.removeChild(space);
1120 
1121 		ref.style.height = origStyle.height;
1122 		ref.style.maxHeight = origStyle.maxHeight;
1123 		if (!(jQuery.browser.msie && jQuery.browser.version < 8)) {
1124 			ref.style.minHeight = origStyle.minHeight;
1125 		}
1126 
1127 		// Allow some leeway in case the zwsp didn't create a whole new line, but
1128 		// only made an existing line slightly higher.  Firefox 6.0a2 shows this
1129 		// behavior when the first line is bold.
1130 		return origHeight < finalHeight - 5;
1131 	}
1132 
1133 	// "An extraneous line break is a br that has no visual effect, in that
1134 	// removing it from the DOM would not change layout, except that a br that is
1135 	// the sole child of an li is not extraneous."
1136 	function isExtraneousLineBreak(br) {
1137 
1138 		if (!isNamedHtmlElement(br, 'br')) {
1139 			return false;
1140 		}
1141 
1142 		if (isNamedHtmlElement(br.parentNode, "li") && br.parentNode.childNodes.length == 1) {
1143 			return false;
1144 		}
1145 
1146 		// Make the line break disappear and see if that changes the block's
1147 		// height.  Yes, this is an absurd hack.  We have to reset height etc. on
1148 		// the reference node because otherwise its height won't change if it's not
1149 		// auto.
1150 		var ref = br.parentNode;
1151 		while ($_.getComputedStyle(ref).display == "inline") {
1152 			ref = ref.parentNode;
1153 		}
1154 
1155 		var origStyle = {
1156 			height: ref.style.height,
1157 			maxHeight: ref.style.maxHeight,
1158 			minHeight: ref.style.minHeight,
1159 			contentEditable: ref.contentEditable
1160 		};
1161 
1162 		ref.style.height = 'auto';
1163 		ref.style.maxHeight = 'none';
1164 		ref.style.minHeight = '0';
1165 		// IE7 would ignore display:none in contentEditable, so we temporarily set it to false
1166 		if (jQuery.browser.msie && jQuery.browser.version <= 7) {
1167 			ref.contentEditable = 'false';
1168 		}
1169 
1170 		var origHeight = ref.offsetHeight;
1171 		if (origHeight == 0) {
1172 			throw "isExtraneousLineBreak: original height is zero, bug?";
1173 		}
1174 
1175 		var origBrDisplay = br.style.display;
1176 		br.style.display = 'none';
1177 		var finalHeight = ref.offsetHeight;
1178 
1179 		// Restore original styles to the touched elements.
1180 		ref.style.height = origStyle.height;
1181 		ref.style.maxHeight = origStyle.maxHeight;
1182 		ref.style.minHeight = origStyle.minHeight;
1183 		// reset contentEditable for IE7
1184 		if (jQuery.browser.msie && jQuery.browser.version <= 7) {
1185 			ref.contentEditable = origStyle.contentEditable;
1186 		}
1187 		br.style.display = origBrDisplay;
1188 
1189 		// https://github.com/alohaeditor/Aloha-Editor/issues/516
1190 		// look like it works in msie > 7
1191 		/* if (jQuery.browser.msie && jQuery.browser.version < 8) {
1192 		   br.removeAttribute("style");
1193 		   ref.removeAttribute("style");
1194 1195 		   } */
1196 
1197 		return origHeight == finalHeight;
1198 	}
1199 
1200 	// "A whitespace node is either a Text node whose data is the empty string; or
1201 	// a Text node whose data consists only of one or more tabs (0x0009), line
1202 	// feeds (0x000A), carriage returns (0x000D), and/or spaces (0x0020), and whose
1203 	// parent is an Element whose resolved value for "white-space" is "normal" or
1204 	// "nowrap"; or a Text node whose data consists only of one or more tabs
1205 	// (0x0009), carriage returns (0x000D), and/or spaces (0x0020), and whose
1206 	// parent is an Element whose resolved value for "white-space" is "pre-line"."
1207 	function isWhitespaceNode(node) {
1208 		var nodeTypes = $_.Node;
1209 		if (node && node.nodeType === nodeTypes.TEXT_NODE) {
1210 			var parentNode = node.parentNode;
1211 
1212 			var nodeData = node.data;
1213 			if (jQuery.trim(nodeData).length === 0) {
1214 				return true;
1215 			} else if (parentNode && /^[\t\n\r ]+$/.test(nodeData)) {
1216 				if (parentNode.nodeType === nodeTypes.ELEMENT_NODE) {
1217 					if (jQuery.inArray($_.getComputedStyle(parentNode).whiteSpace, ["normal", "nowrap"]) !== -1) {
1218 						return true;
1219 					} else if ($_.getComputedStyle(parentNode).whiteSpace === "pre-line") {
1220 						return true;
1221 					}
1222 				} else if (parentNode.nodeType === nodeTypes.DOCUMENT_FRAGMENT_NODE) {
1223 					return true;
1224 				}
1225 			}
1226 		}
1227 		return false;
1228 	}
1229 
1230 	/**
1231 	 * Collapse sequences of ignorable whitespace (tab (0x0009), line feed (0x000A), carriage return (0x000D), space (0x0020)) to only one space.
1232 	 * Preserve the given range if necessary.
1233 	 * @param node text node
1234 	 * @param range range
1235 	 */
1236 	function collapseWhitespace(node, range) {
1237 		// "If node is neither editable nor an editing host, abort these steps."
1238 		if (!isEditable(node) && !isEditingHost(node)) {
1239 			return;
1240 		}
1241 
1242 		// if the given node is not a text node, return
1243 		if (!node || node.nodeType !== $_.Node.TEXT_NODE) {
1244 			return;
1245 		}
1246 
1247 		// if the node is in a pre or pre-wrap node, return
1248 		if (jQuery.inArray($_.getComputedStyle(node.parentNode).whiteSpace, ["pre", "pre-wrap"]) != -1) {
1249 			return;
1250 		}
1251 
1252 		// if the given node does not contain sequences of at least two consecutive ignorable whitespace characters, return
1253 		if (!/[\t\n\r ]{2,}/.test(node.data)) {
1254 			return;
1255 		}
1256 
1257 		var newData = '';
1258 		var correctStart = range.startContainer == node;
1259 		var correctEnd = range.endContainer == node;
1260 		var wsFound = false;
1261 		var i;
1262 
1263 		// iterate through the node data
1264 		for (i = 0; i < node.data.length; ++i) {
1265 			if (/[\t\n\r ]/.test(node.data.substr(i, 1))) {
1266 				// found a whitespace
1267 				if (!wsFound) {
1268 					// this is the first whitespace in the current sequence
1269 					// add a whitespace to the new data sequence
1270 					newData += ' ';
1271 					// remember that we found a whitespace
1272 					wsFound = true;
1273 				} else {
1274 					// this is not the first whitespace in the sequence, so omit this character
1275 					if (correctStart && newData.length < range.startOffset) {
1276 						range.startOffset--;
1277 					}
1278 					if (correctEnd && newData.length < range.endOffset) {
1279 						range.endOffset--;
1280 					}
1281 				}
1282 			} else {
1283 				newData += node.data.substr(i, 1);
1284 				wsFound = false;
1285 			}
1286 		}
1287 
1288 		// set the new data
1289 		node.data = newData;
1290 	}
1291 
1292 	// "node is a collapsed whitespace node if the following algorithm returns
1293 	// true:"
1294 	function isCollapsedWhitespaceNode(node) {
1295 		// "If node is not a whitespace node, return false."
1296 		if (!isWhitespaceNode(node)) {
1297 			return false;
1298 		}
1299 
1300 		// "If node's data is the empty string, return true."
1301 		if (node.data == "") {
1302 			return true;
1303 		}
1304 
1305 		// "Let ancestor be node's parent."
1306 		var ancestor = node.parentNode;
1307 
1308 		// "If ancestor is null, return true."
1309 		if (!ancestor) {
1310 			return true;
1311 		}
1312 
1313 		// "If the "display" property of some ancestor of node has resolved value
1314 		// "none", return true."
1315 		if ($_(getAncestors(node)).some(function (ancestor) { return ancestor.nodeType == $_.Node.ELEMENT_NODE && $_.getComputedStyle(ancestor).display == "none"; })) {
1316 			return true;
1317 		}
1318 
1319 		// "While ancestor is not a block node and its parent is not null, set
1320 		// ancestor to its parent."
1321 		while (!isBlockNode(ancestor) && ancestor.parentNode) {
1322 			ancestor = ancestor.parentNode;
1323 		}
1324 
1325 		// "Let reference be node."
1326 		var reference = node;
1327 
1328 		// "While reference is a descendant of ancestor:"
1329 		while (reference != ancestor) {
1330 			// "Let reference be the node before it in tree order."
1331 			reference = previousNode(reference);
1332 
1333 			// "If reference is a block node or a br, return true."
1334 			if (isBlockNode(reference) || isNamedHtmlElement(reference, 'br')) {
1335 				return true;
1336 			}
1337 
1338 			// "If reference is a Text node that is not a whitespace node, or is an
1339 			// img, break from this loop."
1340 			if ((reference.nodeType == $_.Node.TEXT_NODE && !isWhitespaceNode(reference)) || isNamedHtmlElement(reference, 'img')) {
1341 				break;
1342 			}
1343 		}
1344 
1345 		// "Let reference be node."
1346 		reference = node;
1347 
1348 		// "While reference is a descendant of ancestor:"
1349 		var stop = nextNodeDescendants(ancestor);
1350 		while (reference != stop) {
1351 			// "Let reference be the node after it in tree order, or null if there
1352 			// is no such node."
1353 			reference = nextNode(reference);
1354 
1355 			// "If reference is a block node or a br, return true."
1356 			if (isBlockNode(reference) || isNamedHtmlElement(reference, 'br')) {
1357 				return true;
1358 			}
1359 
1360 			// "If reference is a Text node that is not a whitespace node, or is an
1361 			// img, break from this loop."
1362 			if ((reference && reference.nodeType == $_.Node.TEXT_NODE && !isWhitespaceNode(reference)) || isNamedHtmlElement(reference, 'img')) {
1363 				break;
1364 			}
1365 		}
1366 
1367 		// "Return false."
1368 		return false;
1369 	}
1370 
1371 	// "Something is visible if it is a node that either is a block node, or a Text
1372 	// node that is not a collapsed whitespace node, or an img, or a br that is not
1373 	// an extraneous line break, or any node with a visible descendant; excluding
1374 	// any node with an ancestor container Element whose "display" property has
1375 	// resolved value "none"."
1376 	function isVisible(node) {
1377 		var i;
1378 
1379 		if (!node) {
1380 			return false;
1381 		}
1382 
1383 		if ($_(getAncestors(node).concat(node))
1384 			    .filter(function (node) { return node.nodeType == $_.Node.ELEMENT_NODE; }, true)
1385 			    .some(function (node) { return $_.getComputedStyle(node).display == "none"; })) {
1386 			return false;
1387 		}
1388 
1389 		if (isBlockNode(node) || (node.nodeType == $_.Node.TEXT_NODE && !isCollapsedWhitespaceNode(node)) || isNamedHtmlElement(node, 'img') || (isNamedHtmlElement(node, 'br') && !isExtraneousLineBreak(node))) {
1390 			return true;
1391 		}
1392 
1393 		for (i = 0; i < node.childNodes.length; i++) {
1394 			if (isVisible(node.childNodes[i])) {
1395 				return true;
1396 			}
1397 		}
1398 
1399 		return false;
1400 	}
1401 
1402 	// "Something is invisible if it is a node that is not visible."
1403 	function isInvisible(node) {
1404 		return node && !isVisible(node);
1405 1406 	}
1407 
1408 	// "A collapsed block prop is either a collapsed line break that is not an
1409 	// extraneous line break, or an Element that is an inline node and whose
1410 	// children are all either invisible or collapsed block props and that has at
1411 	// least one child that is a collapsed block prop."
1412 	function isCollapsedBlockProp(node) {
1413 		var i;
1414 
1415 		if (isCollapsedLineBreak(node) && !isExtraneousLineBreak(node)) {
1416 			return true;
1417 		}
1418 
1419 		if (!isInlineNode(node) || node.nodeType != $_.Node.ELEMENT_NODE) {
1420 			return false;
1421 		}
1422 
1423 		var hasCollapsedBlockPropChild = false;
1424 		for (i = 0; i < node.childNodes.length; i++) {
1425 			if (!isInvisible(node.childNodes[i]) && !isCollapsedBlockProp(node.childNodes[i])) {
1426 				return false;
1427 			}
1428 			if (isCollapsedBlockProp(node.childNodes[i])) {
1429 				hasCollapsedBlockPropChild = true;
1430 			}
1431 		}
1432 
1433 		return hasCollapsedBlockPropChild;
1434 	}
1435 
1436 	/**
1437 	 * Checks whether the given node is a visible text node.
1438 	 *
1439 	 * @param {HTMLElement} node
1440 	 * @return {Boolean} True if `node` is a visible text node.
1441 	 */
1442 	function isInvisibleTextNode(node) {
1443 		if (node && node.nodeType !== $_.Node.TEXT_NODE) {
1444 			return false;
1445 		}
1446 		var offset = 0;
1447 		var data = node.data;
1448 		var len = data.length;
1449 		while (offset < len && data.charAt(offset) === '\u200b') {
1450 			offset++;
1451 		}
1452 		return offset === len;
1453 	}
1454 
1455 	/**
1456 	 * Complement of isInvisibleTextNode().
1457 	 *
1458 	 * @param {HTMLElement} node
1459 	 * @return {Boolean} True if `node` is anything but an invisible text node.
1460 	 */
1461 	function isNotInvisibleTextNode(node) {
1462 		return !isInvisibleTextNode(node);
1463 	}
1464 
1465 	/**
1466 	 * Checks whether the given node is a otherwise empty block-level element
1467 	 * containing a propping <br> element.
1468 	 *
1469 	 * @param {HTMLElement} node
1470 	 * @return {Boolean} True if `node` is a propped up block-level element.
1471 	 */
1472 	function isProppedBlock(node) {
1473 		if (!Html.isBlock(node)) {
1474 			return false;
1475 		}
1476 		var child = Html.findNodeRight(node.lastChild, isVisible);
1477 		return (
1478 			child
1479 			&& 'br' === child.nodeName.toLowerCase()
1480 			&& !Html.findNodeRight(child.previousSibling, isVisible)
1481 		);
1482 	}
1483 
1484 	/**
1485 	 * Checks whether the given node is a empty element, or an element that
1486 	 * would otherwise be empty except for a propping <br>, or an element
1487 	 * containing only invisible text nodes.
1488 	 *
1489 	 * @param {HTMLElement} node
1490 	 * @return {Boolean} True if `node` can be considered empty.
1491 	 */
1492 	function isEmptyNode(node) {
1493 		return (
1494 			!node.hasChildNodes()
1495 			|| isProppedBlock(node)
1496 			|| !Html.findNodeRight(node.lastChild, isNotInvisibleTextNode)
1497 		);
1498 	}
1499 
1500 	/**
1501 	 * Check if the given node is a empty element which is the only
1502 	 * immediate child of a editing host.
1503 	 *
1504 	 * @param {HTMLElement} node
1505 	 * @return {Boolean} True if `node` can be regarded as empty and the
1506 	 *                   only immediate child of its parent editing host.
1507 	 */
1508 	function isEmptyOnlyChildOfEditingHost(node) {
1509 		return (
1510 			node
1511 				&& isEmptyNode(node)
1512 					&& isEditingHost(node.parentNode)
1513 						&& !node.previousSibling
1514 							&& !node.nextSibling
1515 		);
1516 	}
1517 
1518 	/**
1519 	 * Remove the given node and return the position from where it was
1520 	 * removed.
1521 	 *
1522 	 * @param {HTMLElement} node Element to remove from DOM
1523 	 * @return {object} Object containing node and offset index.
1524 	 */
1525 	function removeNode(node) {
1526 		var ancestor = node.parentNode;
1527 		var offset = Dom.getIndexInParent(node);
1528 		ancestor.removeChild(node);
1529 		return {
1530 			node: ancestor,
1531 			offset: offset
1532 		};
1533 	}
1534 
1535 	// Please note: This method is deprecated and will be removed.
1536 	// Every command should use the value and range parameter.
1537 	//
1538 	// "The active range is the first range in the Selection given by calling
1539 	// getSelection() on the context object, or null if there is no such range."
1540 	//
1541 	// We cheat and return globalRange if that's defined.  We also ensure that the
1542 	// active range meets the requirements that selection boundary points are
1543 	// supposed to meet, i.e., that the nodes are both Text or Element nodes that
1544 	// descend from a Document.
1545 	function getActiveRange() {
1546 		var ret;
1547 		if (globalRange) {
1548 			ret = globalRange;
1549 		} else if (Aloha.getSelection().rangeCount) {
1550 			ret = Aloha.getSelection().getRangeAt(0);
1551 		} else {
1552 			return null;
1553 		}
1554 		if (jQuery.inArray(ret.startContainer.nodeType, [$_.Node.TEXT_NODE, $_.Node.ELEMENT_NODE]) == -1 || jQuery.inArray(ret.endContainer.nodeType, [$_.Node.TEXT_NODE, $_.Node.ELEMENT_NODE]) == -1 || !ret.startContainer.ownerDocument || !ret.endContainer.ownerDocument || !isDescendant(ret.startContainer, ret.startContainer.ownerDocument) || !isDescendant(ret.endContainer, ret.endContainer.ownerDocument)) {
1555 			throw "Invalid active range; test bug?";
1556 		}
1557 		return ret;
1558 	}
1559 
1560 	// "For some commands, each HTMLDocument must have a boolean state override
1561 	// and/or a string value override. These do not change the command's state or
1562 	// value, but change the way some algorithms behave, as specified in those
1563 	// algorithms' definitions. Initially, both must be unset for every command.
1564 	// Whenever the number of ranges in the Selection changes to something
1565 	// different, and whenever a boundary point of the range at a given index in
1566 	// the Selection changes to something different, the state override and value
1567 	// override must be unset for every command."
1568 	//
1569 	// We implement this crudely by using setters and getters.  To verify that the
1570 	// selection hasn't changed, we copy the active range and just check the
1571 	// endpoints match.  This isn't really correct, but it's good enough for us.
1572 	// Unset state/value overrides are undefined.  We put everything in a function
1573 	// so no one can access anything except via the provided functions, since
1574 	// otherwise callers might mistakenly use outdated overrides (if the selection
1575 	// has changed).
1576 	(function () {
1577 		var stateOverrides = {};
1578 		var valueOverrides = {};
1579 		var storedRange = null;
1580 
1581 		resetOverrides = function (range) {
1582 			if (!storedRange
1583 				    || storedRange.startContainer != range.startContainer
1584 				    || storedRange.endContainer != range.endContainer
1585 				    || storedRange.startOffset != range.startOffset
1586 				    || storedRange.endOffset != range.endOffset) {
1587 				storedRange = {
1588 					startContainer: range.startContainer,
1589 					endContainer: range.endContainer,
1590 					startOffset: range.startOffset,
1591 					endOffset: range.endOffset
1592 				};
1593 				if (!Maps.isEmpty(stateOverrides) || !Maps.isEmpty(valueOverrides)) {
1594 					stateOverrides = {};
1595 					valueOverrides = {};
1596 					return true;
1597 				}
1598 			}
1599 			return false;
1600 		};
1601 
1602 		getStateOverride = function (command, range) {
1603 			resetOverrides(range);
1604 			return stateOverrides[command];
1605 		};
1606 
1607 		setStateOverride = function (command, newState, range) {
1608 			resetOverrides(range);
1609 			stateOverrides[command] = newState;
1610 		};
1611 
1612 		unsetStateOverride = function (command, range) {
1613 			resetOverrides(range);
1614 			delete stateOverrides[command];
1615 		};
1616 
1617 		getValueOverride = function (command, range) {
1618 			resetOverrides(range);
1619 			return valueOverrides[command];
1620 		};
1621 
1622 		// "The value override for the backColor command must be the same as the
1623 		// value override for the hiliteColor command, such that setting one sets
1624 		// the other to the same thing and unsetting one unsets the other."
1625 		setValueOverride = function (command, newValue, range) {
1626 			resetOverrides(range);
1627 			valueOverrides[command] = newValue;
1628 			if (command == "backcolor") {
1629 				valueOverrides.hilitecolor = newValue;
1630 			} else if (command == "hilitecolor") {
1631 				valueOverrides.backcolor = newValue;
1632 			}
1633 		};
1634 
1635 		unsetValueOverride = function (command, range) {
1636 			resetOverrides(range);
1637 			delete valueOverrides[command];
1638 			if (command == "backcolor") {
1639 				delete valueOverrides.hilitecolor;
1640 			} else if (command == "hilitecolor") {
1641 				delete valueOverrides.backcolor;
1642 			}
1643 		};
1644 	}());
1645 
1646 	//@}
1647 
1648 	/////////////////////////////
1649 	///// Common algorithms /////
1650 	/////////////////////////////
1651 
1652 	///// Assorted common algorithms /////
1653 	//@{
1654 
1655 	function movePreservingRanges(node, newParent, newIndex, range) {
1656 		// For convenience, I allow newIndex to be -1 to mean "insert at the end".
1657 		if (newIndex == -1) {
1658 			newIndex = newParent.childNodes.length;
1659 		}
1660 
1661 		// "When the user agent is to move a Node to a new location, preserving
1662 		// ranges, it must remove the Node from its original parent (if any), then
1663 		// insert it in the new location. In doing so, however, it must ignore the
1664 		// regular range mutation rules, and instead follow these rules:"
1665 
1666 		// "Let node be the moved Node, old parent and old index be the old parent
1667 		// (which may be null) and index, and new parent and new index be the new
1668 		// parent and index."
1669 		var oldParent = node.parentNode;
1670 		var oldIndex = Dom.getIndexInParent(node);
1671 		var i;
1672 
1673 		// We only even attempt to preserve the global range object and the ranges
1674 		// in the selection, not every range out there (the latter is probably
1675 		// impossible).
1676 		var ranges = [range];
1677 		for (i = 0; i < Aloha.getSelection().rangeCount; i++) {
1678 			ranges.push(Aloha.getSelection().getRangeAt(i));
1679 		}
1680 		var boundaryPoints = [];
1681 		$_(ranges).forEach(function (range) {
1682 			boundaryPoints.push([range.startContainer, range.startOffset]);
1683 			boundaryPoints.push([range.endContainer, range.endOffset]);
1684 		});
1685 
1686 		$_(boundaryPoints).forEach(function (boundaryPoint) {
1687 			// "If a boundary point's node is the same as or a descendant of node,
1688 			// leave it unchanged, so it moves to the new location."
1689 			//
1690 			// No modifications necessary.
1691 
1692 			// "If a boundary point's node is new parent and its offset is greater
1693 			// than new index, add one to its offset."
1694 			if (boundaryPoint[0] == newParent && boundaryPoint[1] > newIndex) {
1695 				boundaryPoint[1]++;
1696 			}
1697 
1698 			// "If a boundary point's node is old parent and its offset is old index or
1699 			// old index + 1, set its node to new parent and add new index − old index
1700 			// to its offset."
1701 			if (boundaryPoint[0] == oldParent && (boundaryPoint[1] == oldIndex || boundaryPoint[1] == oldIndex + 1)) {
1702 				boundaryPoint[0] = newParent;
1703 				boundaryPoint[1] += newIndex - oldIndex;
1704 			}
1705 
1706 			// "If a boundary point's node is old parent and its offset is greater than
1707 			// old index + 1, subtract one from its offset."
1708 			if (boundaryPoint[0] == oldParent && boundaryPoint[1] > oldIndex + 1) {
1709 				boundaryPoint[1]--;
1710 			}
1711 		});
1712 
1713 		// Now actually move it and preserve the ranges.
1714 		if (newParent.childNodes.length == newIndex) {
1715 			newParent.appendChild(node);
1716 		} else {
1717 			newParent.insertBefore(node, newParent.childNodes[newIndex]);
1718 		}
1719 
1720 		// if we're off actual node boundaries this implies that the move was
1721 		// part of a deletion process (backspace). If that's the case we
1722 		// attempt to fix this by restoring the range to the first index of
1723 		// the node that has been moved
1724 		var newRange = null;
1725 		if (boundaryPoints[0][1] > boundaryPoints[0][0].childNodes.length && boundaryPoints[1][1] > boundaryPoints[1][0].childNodes.length) {
1726 			range.setStart(node, 0);
1727 			range.setEnd(node, 0);
1728 		} else {
1729 			range.setStart(boundaryPoints[0][0], boundaryPoints[0][1]);
1730 			range.setEnd(boundaryPoints[1][0], boundaryPoints[1][1]);
1731 
1732 			Aloha.getSelection().removeAllRanges();
1733 			for (i = 1; i < ranges.length; i++) {
1734 				newRange = Aloha.createRange();
1735 				newRange.setStart(boundaryPoints[2 * i][0], boundaryPoints[2 * i][1]);
1736 				newRange.setEnd(boundaryPoints[2 * i + 1][0], boundaryPoints[2 * i + 1][1]);
1737 				Aloha.getSelection().addRange(newRange);
1738 			}
1739 			if (newRange) {
1740 				range = newRange;
1741 			}
1742 		}
1743 	}
1744 
1745 	/**
1746 	 * Copy all non empty attributes from an existing to a new element
1747 	 *
1748 	 * @param {dom} element The source DOM element
1749 	 * @param {dom} newElement The new DOM element which will get the attributes of the source DOM element
1750 	 * @return void
1751 	 */
1752 	function copyAttributes(element, newElement) {
1753 
1754 		// This is an IE7 workaround. We identified three places that were connected
1755 		// to the mysterious ie7 crash:
1756 		// 1. Add attribute to dom element (Initialization of jquery-ui sortable)
1757 		// 2. Access the jquery expando attribute. Just reading the name is
1758 		//    sufficient to make the browser vulnerable for the crash (Press enter)
1759 		// 3. On editable blur the Aloha.editables[0].getContents(); gets invoked.
1760 		//    This invokation somehow crashes the ie7. We assume that the access of
1761 		//    shared expando attribute updates internal references which are not
1762 		//    correclty handled during clone();
1763 		if (jQuery.browser.msie && jQuery.browser.version >= 7 && typeof element.attributes[jQuery.expando] !== 'undefined') {
1764 			jQuery(element).removeAttr(jQuery.expando);
1765 		}
1766 
1767 		var attrs = element.attributes;
1768 		var i;
1769 		for (i = 0; i < attrs.length; i++) {
1770 			var attr = attrs[i];
1771 			// attr.specified is an IE specific check to exclude attributes that were never really set.
1772 			if (typeof attr.specified === "undefined" || attr.specified) {
1773 				if (typeof newElement.setAttributeNS === 'function') {
1774 					newElement.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
1775 				} else {
1776 					// fixes https://github.com/alohaeditor/Aloha-Editor/issues/515
1777 					newElement.setAttribute(attr.name, attr.value);
1778 				}
1779 			}
1780 		}
1781 	}
1782 
1783 	function setTagName(element, newName, range) {
1784 		// "If element is an HTML element with local name equal to new name, return
1785 		// element."
1786 		if (isNamedHtmlElement(element, newName)) {
1787 			return element;
1788 		}
1789 
1790 		// "If element's parent is null, return element."
1791 		if (!element.parentNode) {
1792 			return element;
1793 		}
1794 
1795 		// "Let replacement element be the result of calling createElement(new
1796 		// name) on the ownerDocument of element."
1797 		var replacementElement = element.ownerDocument.createElement(newName);
1798 
1799 		// "Insert replacement element into element's parent immediately before
1800 		// element."
1801 		element.parentNode.insertBefore(replacementElement, element);
1802 
1803 		// "Copy all attributes of element to replacement element, in order."
1804 		copyAttributes(element, replacementElement);
1805 
1806 		// "While element has children, append the first child of element as the
1807 		// last child of replacement element, preserving ranges."
1808 		while (element.childNodes.length) {
1809 			movePreservingRanges(element.firstChild, replacementElement, replacementElement.childNodes.length, range);
1810 		}
1811 
1812 		// "Remove element from its parent."
1813 		element.parentNode.removeChild(element);
1814 
1815 		// if the range still uses the old element, we modify it to the new one
1816 		if (range.startContainer === element) {
1817 			range.startContainer = replacementElement;
1818 		}
1819 		if (range.endContainer === element) {
1820 			range.endContainer = replacementElement;
1821 		}
1822 
1823 		// "Return replacement element."
1824 		return replacementElement;
1825 	}
1826 
1827 	function removeExtraneousLineBreaksBefore(node) {
1828 		// "Let ref be the previousSibling of node."
1829 		var ref = node.previousSibling;
1830 
1831 		// "If ref is null, abort these steps."
1832 		if (!ref) {
1833 			return;
1834 		}
1835 
1836 		// "While ref has children, set ref to its lastChild."
1837 		while (ref.hasChildNodes()) {
1838 			ref = ref.lastChild;
1839 		}
1840 
1841 		// "While ref is invisible but not an extraneous line break, and ref does
1842 		// not equal node's parent, set ref to the node before it in tree order."
1843 		while (isInvisible(ref) && !isExtraneousLineBreak(ref) && ref != node.parentNode) {
1844 			ref = previousNode(ref);
1845 		}
1846 
1847 		// "If ref is an editable extraneous line break, remove it from its
1848 		// parent."
1849 		if (isEditable(ref) && isExtraneousLineBreak(ref)) {
1850 			ref.parentNode.removeChild(ref);
1851 		}
1852 	}
1853 
1854 	function removeExtraneousLineBreaksAtTheEndOf(node) {
1855 		// "Let ref be node."
1856 		var ref = node;
1857 
1858 		// "While ref has children, set ref to its lastChild."
1859 		while (ref.hasChildNodes()) {
1860 			ref = ref.lastChild;
1861 		}
1862 
1863 		// "While ref is invisible but not an extraneous line break, and ref does
1864 		// not equal node, set ref to the node before it in tree order."
1865 		while (isInvisible(ref) && !isExtraneousLineBreak(ref) && ref != node) {
1866 			ref = previousNode(ref);
1867 1868 		}
1869 
1870 		// "If ref is an editable extraneous line break, remove it from its
1871 		// parent."
1872 		if (isEditable(ref) && isExtraneousLineBreak(ref)) {
1873 			ref.parentNode.removeChild(ref);
1874 		}
1875 	}
1876 
1877 	// "To remove extraneous line breaks from a node, first remove extraneous line
1878 	// breaks before it, then remove extraneous line breaks at the end of it."
1879 	function removeExtraneousLineBreaksFrom(node) {
1880 		removeExtraneousLineBreaksBefore(node);
1881 		removeExtraneousLineBreaksAtTheEndOf(node);
1882 	}
1883 
1884 	//@}
1885 	///// Wrapping a list of nodes /////
1886 	//@{
1887 
1888 	function wrap(nodeList, siblingCriteria, newParentInstructions, range) {
1889 		var i;
1890 
1891 		// "If not provided, sibling criteria returns false and new parent
1892 		// instructions returns null."
1893 		if (typeof siblingCriteria == "undefined") {
1894 			siblingCriteria = function () {
1895 				return false;
1896 			};
1897 		}
1898 		if (typeof newParentInstructions == "undefined") {
1899 			newParentInstructions = function () {
1900 1901 				return null;
1902 			};
1903 		}
1904 
1905 		// "If node list is empty, or the first member of node list is not
1906 		// editable, return null and abort these steps."
1907 		if (!nodeList.length || !isEditable(nodeList[0])) {
1908 			return null;
1909 		}
1910 
1911 		// "If node list's last member is an inline node that's not a br, and node
1912 		// list's last member's nextSibling is a br, append that br to node list."
1913 		if (isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "br") && isNamedHtmlElement(nodeList[nodeList.length - 1].nextSibling, "br")) {
1914 			nodeList.push(nodeList[nodeList.length - 1].nextSibling);
1915 		}
1916 
1917 		// "If the previousSibling of the first member of node list is editable and
1918 		// running sibling criteria on it returns true, let new parent be the
1919 		// previousSibling of the first member of node list."
1920 		var newParent;
1921 		if (isEditable(nodeList[0].previousSibling) && siblingCriteria(nodeList[0].previousSibling)) {
1922 			newParent = nodeList[0].previousSibling;
1923 
1924 			// "Otherwise, if the nextSibling of the last member of node list is
1925 			// editable and running sibling criteria on it returns true, let new parent
1926 			// be the nextSibling of the last member of node list."
1927 		} else if (isEditable(nodeList[nodeList.length - 1].nextSibling) && siblingCriteria(nodeList[nodeList.length - 1].nextSibling)) {
1928 			newParent = nodeList[nodeList.length - 1].nextSibling;
1929 
1930 			// "Otherwise, run new parent instructions, and let new parent be the
1931 			// result."
1932 		} else {
1933 			newParent = newParentInstructions();
1934 		}
1935 
1936 		// "If new parent is null, abort these steps and return null."
1937 1938 		if (!newParent) {
1939 			return null;
1940 		}
1941 
1942 		// "If new parent's parent is null:"
1943 		var newParentParentNode = newParent.parentNode;
1944 		if (!newParentParentNode) {
1945 			// "Insert new parent into the parent of the first member of node list
1946 			// immediately before the first member of node list."
1947 			nodeList[0].parentNode.insertBefore(newParent, nodeList[0]);
1948 
1949 			// "If any range has a boundary point with node equal to the parent of
1950 			// new parent and offset equal to the index of new parent, add one to
1951 			// that boundary point's offset."
1952 			//
1953 			// Try to fix range
1954 			var startContainer = range.startContainer,
1955 				startOffset = range.startOffset,
1956 				endContainer = range.endContainer,
1957 				endOffset = range.endOffset,
1958 			    newParentIndex = Dom.getIndexInParent(newParent);
1959 
1960 			if (startOffset >= newParentIndex && startContainer == newParentParentNode) {
1961 				range.setStart(startContainer, startOffset + 1);
1962 			}
1963 			if (endOffset >= newParentIndex && endContainer == newParentParentNode) {
1964 				range.setEnd(endContainer, endOffset + 1);
1965 			}
1966 
1967 			// Only try to fix the global range. TODO remove globalRange here
1968 			if (globalRange && globalRange !== range) {
1969 				startContainer = globalRange.startContainer;
1970 				startOffset = globalRange.startOffset;
1971 				endContainer = globalRange.endContainer;
1972 				endOffset = globalRange.endOffset;
1973 				if (startContainer == newParentParentNode && startOffset >= newParentIndex) {
1974 					globalRange.setStart(startContainer, startOffset + 1);
1975 				}
1976 				if (endContainer == newParentParentNode && endOffset >= newParentIndex) {
1977 					globalRange.setEnd(endContainer, endOffset + 1);
1978 				}
1979 			}
1980 		}
1981 
1982 		// "Let original parent be the parent of the first member of node list."
1983 		var originalParent = nodeList[0].parentNode;
1984 
1985 		// "If new parent is before the first member of node list in tree order:"
1986 		if (isBefore(newParent, nodeList[0])) {
1987 			// "If new parent is not an inline node, but the last child of new
1988 			// parent and the first member of node list are both inline nodes, and
1989 			// the last child of new parent is not a br, call createElement("br")
1990 			// on the ownerDocument of new parent and append the result as the last
1991 			// child of new parent."
1992 			if (!isInlineNode(newParent) && isInlineNode(newParent.lastChild) && isInlineNode(nodeList[0]) && !isNamedHtmlElement(newParent.lastChild, "BR")) {
1993 				newParent.appendChild(newParent.ownerDocument.createElement("br"));
1994 			}
1995 
1996 			// "For each node in node list, append node as the last child of new
1997 			// parent, preserving ranges."
1998 			for (i = 0; i < nodeList.length; i++) {
1999 				movePreservingRanges(nodeList[i], newParent, -1, range);
2000 			}
2001 
2002 			// "Otherwise:"
2003 		} else {
2004 			// "If new parent is not an inline node, but the first child of new
2005 			// parent and the last member of node list are both inline nodes, and
2006 			// the last member of node list is not a br, call createElement("br")
2007 			// on the ownerDocument of new parent and insert the result as the
2008 			// first child of new parent."
2009 			if (!isInlineNode(newParent) && isInlineNode(newParent.firstChild) && isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "BR")) {
2010 				newParent.insertBefore(newParent.ownerDocument.createElement("br"), newParent.firstChild);
2011 			}
2012 
2013 			// "For each node in node list, in reverse order, insert node as the
2014 			// first child of new parent, preserving ranges."
2015 			for (i = nodeList.length - 1; i >= 0; i--) {
2016 				movePreservingRanges(nodeList[i], newParent, 0, range);
2017 			}
2018 		}
2019 
2020 		// "If original parent is editable and has no children, remove it from its
2021 		// parent."
2022 		if (isEditable(originalParent) && !originalParent.hasChildNodes()) {
2023 			originalParent.parentNode.removeChild(originalParent);
2024 		}
2025 
2026 		// "If new parent's nextSibling is editable and running sibling criteria on
2027 		// it returns true:"
2028 		if (isEditable(newParent.nextSibling) && siblingCriteria(newParent.nextSibling)) {
2029 			// "If new parent is not an inline node, but new parent's last child
2030 			// and new parent's nextSibling's first child are both inline nodes,
2031 			// and new parent's last child is not a br, call createElement("br") on
2032 			// the ownerDocument of new parent and append the result as the last
2033 			// child of new parent."
2034 			if (!isInlineNode(newParent) && isInlineNode(newParent.lastChild) && isInlineNode(newParent.nextSibling.firstChild) && !isNamedHtmlElement(newParent.lastChild, "BR")) {
2035 				newParent.appendChild(newParent.ownerDocument.createElement("br"));
2036 			}
2037 
2038 			// "While new parent's nextSibling has children, append its first child
2039 			// as the last child of new parent, preserving ranges."
2040 			while (newParent.nextSibling.hasChildNodes()) {
2041 				movePreservingRanges(newParent.nextSibling.firstChild, newParent, -1, range);
2042 			}
2043 
2044 			// "Remove new parent's nextSibling from its parent."
2045 			newParentParentNode.removeChild(newParent.nextSibling);
2046 		}
2047 
2048 		// "Remove extraneous line breaks from new parent."
2049 		removeExtraneousLineBreaksFrom(newParent);
2050 
2051 		// "Return new parent."
2052 		return newParent;
2053 	}
2054 
2055 
2056 	//@}
2057 	///// Allowed children /////
2058 	//@{
2059 
2060 	// "A name of an element with inline contents is "a", "abbr", "b", "bdi",
2061 	// "bdo", "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i",
2062 	// "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small",
2063 	// "span", "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike",
2064 	// "xmp", "big", "blink", "font", "marquee", "nobr", or "tt"."
2065 	var namesOfElementsWithInlineContentsMap = {
2066 		"A": true,
2067 		"ABBR": true,
2068 		"B": true,
2069 		"BDI": true,
2070 		"BDO": true,
2071 		"CITE": true,
2072 		"CODE": true,
2073 		"DFN": true,
2074 		"EM": true,
2075 		"H1": true,
2076 		"H2": true,
2077 		"H3": true,
2078 		"H4": true,
2079 		"H5": true,
2080 		"H6": true,
2081 		"I": true,
2082 		"KBD": true,
2083 		"MARK": true,
2084 		"P": true,
2085 		"PRE": true,
2086 		"Q": true,
2087 		"RP": true,
2088 		"RT": true,
2089 		"RUBY": true,
2090 		"S": true,
2091 		"SAMP": true,
2092 		"SMALL": true,
2093 		"SPAN": true,
2094 		"STRONG": true,
2095 		"SUB": true,
2096 		"SUP": true,
2097 		"U": true,
2098 		"VAR": true,
2099 		"ACRONYM": true,
2100 		"LISTING": true,
2101 		"STRIKE": true,
2102 		"XMP": true,
2103 		"BIG": true,
2104 		"BLINK": true,
2105 		"FONT": true,
2106 		"MARQUEE": true,
2107 		"NOBR": true,
2108 		"TT": true
2109 	};
2110 
2111 
2112 	var tableRelatedElements = {
2113 		"colgroup": true,
2114 		"table": true,
2115 		"tbody": true,
2116 		"tfoot": true,
2117 		"thead": true,
2118 		"tr": true
2119 	};
2120 
2121 	var scriptRelatedElements = {
2122 		"script": true,
2123 		"style": true,
2124 		"plaintext": true,
2125 		"xmp": true
2126 	};
2127 
2128 	var prohibitedHeadingNestingMap = jQuery.extend({
2129 		"H1": true,
2130 		"H2": true,
2131 		"H3": true,
2132 		"H4": true,
2133 		"H5": true,
2134 		"H6": true
2135 	}, prohibitedParagraphChildNamesMap);
2136 	var prohibitedTableNestingMap = {
2137 		"CAPTION": true,
2138 		"COL": true,
2139 		"COLGROUP": true,
2140 		"TBODY": true,
2141 		"TD": true,
2142 		"TFOOT": true,
2143 		"TH": true,
2144 		"THEAD": true,
2145 		"TR": true
2146 	};
2147 	var prohibitedDefNestingMap = {
2148 		"DD": true,
2149 		"DT": true
2150 	};
2151 	var prohibitedNestingCombinationsMap = {
2152 		"A": jQuery.extend({
2153 			"A": true
2154 		}, prohibitedParagraphChildNamesMap),
2155 		"DD": prohibitedDefNestingMap,
2156 		"DT": prohibitedDefNestingMap,
2157 		"LI": {
2158 			"LI": true
2159 		},
2160 		"NOBR": jQuery.extend({
2161 			"NOBR": true
2162 		}, prohibitedParagraphChildNamesMap),
2163 		"H1": prohibitedHeadingNestingMap,
2164 		"H2": prohibitedHeadingNestingMap,
2165 		"H3": prohibitedHeadingNestingMap,
2166 2167 		"H4": prohibitedHeadingNestingMap,
2168 		"H5": prohibitedHeadingNestingMap,
2169 		"H6": prohibitedHeadingNestingMap,
2170 		"TD": prohibitedTableNestingMap,
2171 		"TH": prohibitedTableNestingMap,
2172 		// this is the same as namesOfElementsWithInlineContentsMap excluding a and h1-h6 elements above
2173 		"ABBR": prohibitedParagraphChildNamesMap,
2174 		"B": prohibitedParagraphChildNamesMap,
2175 		"BDI": prohibitedParagraphChildNamesMap,
2176 		"BDO": prohibitedParagraphChildNamesMap,
2177 		"CITE": prohibitedParagraphChildNamesMap,
2178 		"CODE": prohibitedParagraphChildNamesMap,
2179 		"DFN": prohibitedParagraphChildNamesMap,
2180 		"EM": prohibitedParagraphChildNamesMap,
2181 		"I": prohibitedParagraphChildNamesMap,
2182 		"KBD": prohibitedParagraphChildNamesMap,
2183 		"MARK": prohibitedParagraphChildNamesMap,
2184 		"P": prohibitedParagraphChildNamesMap,
2185 		"PRE": prohibitedParagraphChildNamesMap,
2186 		"Q": prohibitedParagraphChildNamesMap,
2187 		"RP": prohibitedParagraphChildNamesMap,
2188 		"RT": prohibitedParagraphChildNamesMap,
2189 		"RUBY": prohibitedParagraphChildNamesMap,
2190 		"S": prohibitedParagraphChildNamesMap,
2191 		"SAMP": prohibitedParagraphChildNamesMap,
2192 		"SMALL": prohibitedParagraphChildNamesMap,
2193 		"SPAN": prohibitedParagraphChildNamesMap,
2194 		"STRONG": prohibitedParagraphChildNamesMap,
2195 		"SUB": prohibitedParagraphChildNamesMap,
2196 		"SUP": prohibitedParagraphChildNamesMap,
2197 		"U": prohibitedParagraphChildNamesMap,
2198 		"VAR": prohibitedParagraphChildNamesMap,
2199 		"ACRONYM": prohibitedParagraphChildNamesMap,
2200 		"LISTING": prohibitedParagraphChildNamesMap,
2201 		"STRIKE": prohibitedParagraphChildNamesMap,
2202 		"XMP": prohibitedParagraphChildNamesMap,
2203 		"BIG": prohibitedParagraphChildNamesMap,
2204 		"BLINK": prohibitedParagraphChildNamesMap,
2205 		"FONT": prohibitedParagraphChildNamesMap,
2206 2207 		"MARQUEE": prohibitedParagraphChildNamesMap,
2208 		"TT": prohibitedParagraphChildNamesMap
2209 	};
2210 
2211 	// "An element with inline contents is an HTML element whose local name is a
2212 	// name of an element with inline contents."
2213 	function isElementWithInlineContents(node) {
2214 		return isMappedHtmlElement(node, namesOfElementsWithInlineContentsMap);
2215 	}
2216 
2217 	function isAllowedChild(child, parent_) {
2218 		// "If parent is "colgroup", "table", "tbody", "tfoot", "thead", "tr", or
2219 		// an HTML element with local name equal to one of those, and child is a
2220 		// Text node whose data does not consist solely of space characters, return
2221 		// false."
2222 		if ((tableRelatedElements[parent_] || isHtmlElementInArray(parent_, ["colgroup", "table", "tbody", "tfoot", "thead", "tr"])) && typeof child == "object" && child.nodeType == $_.Node.TEXT_NODE && !/^[ \t\n\f\r]*$/.test(child.data)) {
2223 			return false;
2224 		}
2225 
2226 		// "If parent is "script", "style", "plaintext", or "xmp", or an HTML
2227 		// element with local name equal to one of those, and child is not a Text
2228 		// node, return false."
2229 		if ((scriptRelatedElements[parent_] || isHtmlElementInArray(parent_, ["script", "style", "plaintext", "xmp"])) && (typeof child != "object" || child.nodeType != $_.Node.TEXT_NODE)) {
2230 			return false;
2231 		}
2232 
2233 		// "If child is a Document, DocumentFragment, or DocumentType, return
2234 		// false."
2235 		if (typeof child == "object" && (child.nodeType == $_.Node.DOCUMENT_NODE || child.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE || child.nodeType == $_.Node.DOCUMENT_TYPE_NODE)) {
2236 			return false;
2237 		}
2238 
2239 		// "If child is an HTML element, set child to the local name of child."
2240 		if (isAnyHtmlElement(child)) {
2241 			child = child.tagName.toLowerCase();
2242 		}
2243 
2244 		// "If child is not a string, return true."
2245 		if (typeof child != "string") {
2246 			return true;
2247 		}
2248 
2249 		// "If parent is an HTML element:"
2250 		if (isAnyHtmlElement(parent_)) {
2251 			// "If child is "a", and parent or some ancestor of parent is an a,
2252 			// return false."
2253 			//
2254 			// "If child is a prohibited paragraph child name and parent or some
2255 			// ancestor of parent is an element with inline contents, return
2256 			// false."
2257 			//
2258 			// "If child is "h1", "h2", "h3", "h4", "h5", or "h6", and parent or
2259 			// some ancestor of parent is an HTML element with local name "h1",
2260 			// "h2", "h3", "h4", "h5", or "h6", return false."
2261 			var ancestor = parent_;
2262 			while (ancestor) {
2263 				if (child == "a" && isNamedHtmlElement(ancestor, 'a')) {
2264 					return false;
2265 				}
2266 				if (prohibitedParagraphChildNamesMap[child.toUpperCase()] && isElementWithInlineContents(ancestor)) {
2267 					return false;
2268 				}
2269 				if (/^h[1-6]$/.test(child) && isAnyHtmlElement(ancestor) && /^H[1-6]$/.test(ancestor.tagName)) {
2270 					return false;
2271 				}
2272 				ancestor = ancestor.parentNode;
2273 			}
2274 
2275 			// "Let parent be the local name of parent."
2276 			parent_ = parent_.tagName.toLowerCase();
2277 		}
2278 
2279 		// "If parent is an Element or DocumentFragment, return true."
2280 		if (typeof parent_ == "object" && (parent_.nodeType == $_.Node.ELEMENT_NODE || parent_.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE)) {
2281 			return true;
2282 		}
2283 
2284 		// "If parent is not a string, return false."
2285 		if (typeof parent_ != "string") {
2286 			return false;
2287 		}
2288 
2289 		// "If parent is on the left-hand side of an entry on the following list,
2290 		// then return true if child is listed on the right-hand side of that
2291 		// entry, and false otherwise."
2292 		switch (parent_) {
2293 		case "colgroup":
2294 			return child == "col";
2295 		case "table":
2296 			return jQuery.inArray(child, ["caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"]) != -1;
2297 		case "tbody":
2298 		case "thead":
2299 		case "tfoot":
2300 			return jQuery.inArray(child, ["td", "th", "tr"]) != -1;
2301 		case "tr":
2302 			return jQuery.inArray(child, ["td", "th"]) != -1;
2303 		case "dl":
2304 			return jQuery.inArray(child, ["dt", "dd"]) != -1;
2305 		case "dir":
2306 		case "ol":
2307 		case "ul":
2308 			return jQuery.inArray(child, ["dir", "li", "ol", "ul"]) != -1;
2309 		case "hgroup":
2310 			return (/^h[1-6]$/).test(child);
2311 		}
2312 
2313 		// "If child is "body", "caption", "col", "colgroup", "frame", "frameset",
2314 		// "head", "html", "tbody", "td", "tfoot", "th", "thead", or "tr", return
2315 		// false."
2316 		if (jQuery.inArray(child, ["body", "caption", "col", "colgroup", "frame", "frameset", "head", "html", "tbody", "td", "tfoot", "th", "thead", "tr"]) != -1) {
2317 			return false;
2318 		}
2319 
2320 		// "If child is "dd" or "dt" and parent is not "dl", return false."
2321 		if (jQuery.inArray(child, ["dd", "dt"]) != -1 && parent_ != "dl") {
2322 			return false;
2323 2324 		}
2325 
2326 		// "If child is "li" and parent is not "ol" or "ul", return false."
2327 		if (child == "li" && parent_ != "ol" && parent_ != "ul") {
2328 			return false;
2329 		}
2330 
2331 		// "If parent is on the left-hand side of an entry on the following list
2332 		// and child is listed on the right-hand side of that entry, return false."
2333 		var leftSide = prohibitedNestingCombinationsMap[parent_.toUpperCase()];
2334 		if (leftSide) {
2335 			var rightSide = leftSide[child.toUpperCase()];
2336 			if (rightSide) {
2337 				return false;
2338 			}
2339 		}
2340 
2341 		// "Return true."
2342 		return true;
2343 	}
2344 
2345 
2346 	//@}
2347 
2348 	//////////////////////////////////////
2349 	///// Inline formatting commands /////
2350 	//////////////////////////////////////
2351 
2352 	///// Inline formatting command definitions /////
2353 	//@{
2354 
2355 	// "A node node is effectively contained in a range range if range is not
2356 	// collapsed, and at least one of the following holds:"
2357 	function isEffectivelyContained(node, range) {
2358 		if (range.collapsed) {
2359 			return false;
2360 		}
2361 
2362 		// "node is contained in range."
2363 		if (isContained(node, range)) {
2364 			return true;
2365 		}
2366 
2367 		// "node is range's start node, it is a Text node, and its length is
2368 		// different from range's start offset."
2369 		if (node == range.startContainer && node.nodeType == $_.Node.TEXT_NODE && getNodeLength(node) != range.startOffset) {
2370 			return true;
2371 		}
2372 
2373 		// "node is range's end node, it is a Text node, and range's end offset is
2374 		// not 0."
2375 		if (node == range.endContainer && node.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0) {
2376 			return true;
2377 		}
2378 
2379 		// "node has at least one child; and all its children are effectively
2380 		// contained in range; and either range's start node is not a descendant of
2381 		// node or is not a Text node or range's start offset is zero; and either
2382 		// range's end node is not a descendant of node or is not a Text node or
2383 		// range's end offset is its end node's length."
2384 		if (node.hasChildNodes() && $_(node.childNodes).every(function (child) { return isEffectivelyContained(child, range); })
2385 			    && (!isDescendant(range.startContainer, node)
2386 					|| range.startContainer.nodeType != $_.Node.TEXT_NODE
2387 					|| range.startOffset == 0)
2388 			    && (!isDescendant(range.endContainer, node)
2389 					|| range.endContainer.nodeType != $_.Node.TEXT_NODE
2390 					|| range.endOffset == getNodeLength(range.endContainer))) {
2391 			return true;
2392 		}
2393 
2394 		return false;
2395 	}
2396 
2397 	// Like get(All)ContainedNodes(), but for effectively contained nodes.
2398 	function getEffectivelyContainedNodes(range, condition) {
2399 		if (typeof condition == "undefined") {
2400 			condition = function () {
2401 				return true;
2402 			};
2403 		}
2404 		var node = range.startContainer;
2405 		while (isEffectivelyContained(node.parentNode, range)) {
2406 			node = node.parentNode;
2407 		}
2408 
2409 		var stop = nextNodeDescendants(range.endContainer);
2410 
2411 		var nodeList = [];
2412 		while (isBefore(node, stop)) {
2413 			if (isEffectivelyContained(node, range) && condition(node)) {
2414 				nodeList.push(node);
2415 				node = nextNodeDescendants(node);
2416 				continue;
2417 			}
2418 			node = nextNode(node);
2419 		}
2420 		return nodeList;
2421 	}
2422 
2423 	function getAllEffectivelyContainedNodes(range, condition) {
2424 		if (typeof condition == "undefined") {
2425 			condition = function () {
2426 				return true;
2427 			};
2428 		}
2429 		var node = range.startContainer;
2430 		while (isEffectivelyContained(node.parentNode, range)) {
2431 			node = node.parentNode;
2432 		}
2433 
2434 		var stop = nextNodeDescendants(range.endContainer);
2435 
2436 		var nodeList = [];
2437 		while (isBefore(node, stop)) {
2438 			if (isEffectivelyContained(node, range) && condition(node)) {
2439 				nodeList.push(node);
2440 			}
2441 			node = nextNode(node);
2442 		}
2443 		return nodeList;
2444 	}
2445 
2446 	// "A modifiable element is a b, em, i, s, span, strong, sub, sup, or u element
2447 	// with no attributes except possibly style; or a font element with no
2448 	// attributes except possibly style, color, face, and/or size; or an a element
2449 	// with no attributes except possibly style and/or href."
2450 	function isModifiableElement(node) {
2451 		if (!isAnyHtmlElement(node)) {
2452 			return false;
2453 		}
2454 
2455 		if (jQuery.inArray(node.tagName, ["B", "EM", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"]) != -1) {
2456 			if (node.attributes.length == 0) {
2457 				return true;
2458 			}
2459 
2460 			if (node.attributes.length == 1 && hasAttribute(node, "style")) {
2461 				return true;
2462 			}
2463 		}
2464 
2465 		if (node.tagName == "FONT" || node.tagName == "A") {
2466 			var numAttrs = node.attributes.length;
2467 
2468 			if (hasAttribute(node, "style")) {
2469 				numAttrs--;
2470 			}
2471 
2472 			if (node.tagName == "FONT") {
2473 				if (hasAttribute(node, "color")) {
2474 					numAttrs--;
2475 				}
2476 
2477 				if (hasAttribute(node, "face")) {
2478 					numAttrs--;
2479 				}
2480 
2481 				if (hasAttribute(node, "size")) {
2482 					numAttrs--;
2483 				}
2484 			}
2485 
2486 			if (node.tagName == "A" && hasAttribute(node, "href")) {
2487 				numAttrs--;
2488 			}
2489 
2490 			if (numAttrs == 0) {
2491 				return true;
2492 			}
2493 		}
2494 
2495 		return false;
2496 	}
2497 
2498 	function isSimpleModifiableElement(node) {
2499 		// "A simple modifiable element is an HTML element for which at least one
2500 		// of the following holds:"
2501 		if (!isAnyHtmlElement(node)) {
2502 			return false;
2503 		}
2504 
2505 		// Only these elements can possibly be a simple modifiable element.
2506 		if (jQuery.inArray(node.tagName, ["A", "B", "EM", "FONT", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"]) == -1) {
2507 			return false;
2508 		}
2509 
2510 		// "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u
2511 		// element with no attributes."
2512 		if (node.attributes.length == 0) {
2513 			return true;
2514 		}
2515 
2516 		// If it's got more than one attribute, everything after this fails.
2517 		if (node.attributes.length > 1) {
2518 			return false;
2519 		}
2520 
2521 		// "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u
2522 		// element with exactly one attribute, which is style, which sets no CSS
2523 		// properties (including invalid or unrecognized properties)."
2524 		//
2525 		// Not gonna try for invalid or unrecognized.
2526 		if (hasAttribute(node, "style") && getStyleLength(node) == 0) {
2527 			return true;
2528 		}
2529 
2530 		// "It is an a element with exactly one attribute, which is href."
2531 		if (node.tagName == "A" && hasAttribute(node, "href")) {
2532 			return true;
2533 		}
2534 
2535 		// "It is a font element with exactly one attribute, which is either color,
2536 		// face, or size."
2537 		if (node.tagName == "FONT" && (hasAttribute(node, "color") || hasAttribute(node, "face") || hasAttribute(node, "size"))) {
2538 			return true;
2539 		}
2540 
2541 		// "It is a b or strong element with exactly one attribute, which is style,
2542 		// and the style attribute sets exactly one CSS property (including invalid
2543 		// or unrecognized properties), which is "font-weight"."
2544 		if ((node.tagName == "B" || node.tagName == "STRONG") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.fontWeight != "") {
2545 			return true;
2546 		}
2547 
2548 		// "It is an i or em element with exactly one attribute, which is style,
2549 		// and the style attribute sets exactly one CSS property (including invalid
2550 		// or unrecognized properties), which is "font-style"."
2551 		if ((node.tagName == "I" || node.tagName == "EM") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.fontStyle != "") {
2552 			return true;
2553 		}
2554 
2555 		// "It is an a, font, or span element with exactly one attribute, which is
2556 		// style, and the style attribute sets exactly one CSS property (including
2557 		// invalid or unrecognized properties), and that property is not
2558 		// "text-decoration"."
2559 		if ((node.tagName == "A" || node.tagName == "FONT" || node.tagName == "SPAN") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.textDecoration == "") {
2560 			return true;
2561 		}
2562 
2563 		// "It is an a, font, s, span, strike, or u element with exactly one
2564 		// attribute, which is style, and the style attribute sets exactly one CSS
2565 		// property (including invalid or unrecognized properties), which is
2566 		// "text-decoration", which is set to "line-through" or "underline" or
2567 		// "overline" or "none"."
2568 		if (jQuery.inArray(node.tagName, ["A", "FONT", "S", "SPAN", "STRIKE", "U"]) != -1 && hasAttribute(node, "style") && getStyleLength(node) == 1 && (node.style.textDecoration == "line-through" || node.style.textDecoration == "underline" || node.style.textDecoration == "overline" || node.style.textDecoration == "none")) {
2569 			return true;
2570 		}
2571 
2572 		return false;
2573 	}
2574 
2575 	// "Two quantities are equivalent values for a command if either both are null,
2576 	// or both are strings and they're equal and the command does not define any
2577 	// equivalent values, or both are strings and the command defines equivalent
2578 	// values and they match the definition."
2579 	function areEquivalentValues(command, val1, val2) {
2580 		if (val1 === null && val2 === null) {
2581 			return true;
2582 		}
2583 
2584 		if (typeof val1 == "string" && typeof val2 == "string" && val1 == val2 && !(commands[command].hasOwnProperty("equivalentValues"))) {
2585 			return true;
2586 		}
2587 
2588 		if (typeof val1 == "string" && typeof val2 == "string" && commands[command].hasOwnProperty("equivalentValues") && commands[command].equivalentValues(val1, val2)) {
2589 			return true;
2590 		}
2591 
2592 		return false;
2593 	}
2594 
2595 	// "Two quantities are loosely equivalent values for a command if either they
2596 	// are equivalent values for the command, or if the command is the fontSize
2597 	// command; one of the quantities is one of "xx-small", "small", "medium",
2598 	// "large", "x-large", "xx-large", or "xxx-large"; and the other quantity is
2599 	// the resolved value of "font-size" on a font element whose size attribute has
2600 	// the corresponding value set ("1" through "7" respectively)."
2601 	function areLooselyEquivalentValues(command, val1, val2) {
2602 		if (areEquivalentValues(command, val1, val2)) {
2603 			return true;
2604 		}
2605 
2606 		if (command != "fontsize" || typeof val1 != "string" || typeof val2 != "string") {
2607 			return false;
2608 		}
2609 
2610 		// Static variables in JavaScript?
2611 		var callee = areLooselyEquivalentValues;
2612 		if (callee.sizeMap === undefined) {
2613 			callee.sizeMap = {};
2614 			var font = document.createElement("font");
2615 			document.body.appendChild(font);
2616 			$_(["xx-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]).forEach(function (keyword) {
2617 				font.size = cssSizeToLegacy(keyword);
2618 				callee.sizeMap[keyword] = $_.getComputedStyle(font).fontSize;
2619 			});
2620 			document.body.removeChild(font);
2621 		}
2622 
2623 		return val1 === callee.sizeMap[val2] || val2 === callee.sizeMap[val1];
2624 	}
2625 
2626 	//@}
2627 	///// Assorted inline formatting command algorithms /////
2628 	//@{
2629 
2630 	function getEffectiveCommandValue(node, command) {
2631 		// "If neither node nor its parent is an Element, return null."
2632 		if (node.nodeType != $_.Node.ELEMENT_NODE && (!node.parentNode || node.parentNode.nodeType != $_.Node.ELEMENT_NODE)) {
2633 			return null;
2634 		}
2635 
2636 		// "If node is not an Element, return the effective command value of its
2637 		// parent for command."
2638 		if (node.nodeType != $_.Node.ELEMENT_NODE) {
2639 			return getEffectiveCommandValue(node.parentNode, command);
2640 		}
2641 
2642 		// "If command is "createLink" or "unlink":"
2643 		if (command == "createlink" || command == "unlink") {
2644 			// "While node is not null, and is not an a element that has an href
2645 			// attribute, set node to its parent."
2646 			while (node && (!isAnyHtmlElement(node) || node.tagName != "A" || !hasAttribute(node, "href"))) {
2647 				node = node.parentNode;
2648 			}
2649 
2650 			// "If node is null, return null."
2651 			if (!node) {
2652 				return null;
2653 			}
2654 
2655 			// "Return the value of node's href attribute."
2656 			return node.getAttribute("href");
2657 		}
2658 
2659 		// "If command is "backColor" or "hiliteColor":"
2660 		if (command == "backcolor" || command == "hilitecolor") {
2661 			// "While the resolved value of "background-color" on node is any
2662 			// fully transparent value, and node's parent is an Element, set
2663 			// node to its parent."
2664 			//
2665 			// Another lame hack to avoid flawed APIs.
2666 			while (($_.getComputedStyle(node).backgroundColor == "rgba(0, 0, 0, 0)" || $_.getComputedStyle(node).backgroundColor === "" || $_.getComputedStyle(node).backgroundColor == "transparent") && node.parentNode && node.parentNode.nodeType == $_.Node.ELEMENT_NODE) {
2667 				node = node.parentNode;
2668 			}
2669 
2670 			// "If the resolved value of "background-color" on node is a fully
2671 			// transparent value, return "rgb(255, 255, 255)"."
2672 			if ($_.getComputedStyle(node).backgroundColor == "rgba(0, 0, 0, 0)" || $_.getComputedStyle(node).backgroundColor === "" || $_.getComputedStyle(node).backgroundColor == "transparent") {
2673 				return "rgb(255, 255, 255)";
2674 			}
2675 
2676 			// "Otherwise, return the resolved value of "background-color" for
2677 			// node."
2678 			return $_.getComputedStyle(node).backgroundColor;
2679 		}
2680 
2681 		// "If command is "subscript" or "superscript":"
2682 		if (command == "subscript" || command == "superscript") {
2683 			// "Let affected by subscript and affected by superscript be two
2684 			// boolean variables, both initially false."
2685 			var affectedBySubscript = false;
2686 			var affectedBySuperscript = false;
2687 
2688 			// "While node is an inline node:"
2689 			while (isInlineNode(node)) {
2690 				var verticalAlign = $_.getComputedStyle(node).verticalAlign;
2691 
2692 				// "If node is a sub, set affected by subscript to true."
2693 				if (isNamedHtmlElement(node, 'sub')) {
2694 					affectedBySubscript = true;
2695 					// "Otherwise, if node is a sup, set affected by superscript to
2696 					// true."
2697 				} else if (isNamedHtmlElement(node, 'sup')) {
2698 					affectedBySuperscript = true;
2699 				}
2700 
2701 				// "Set node to its parent."
2702 				node = node.parentNode;
2703 			}
2704 
2705 			// "If affected by subscript and affected by superscript are both true,
2706 			// return the string "mixed"."
2707 			if (affectedBySubscript && affectedBySuperscript) {
2708 				return "mixed";
2709 			}
2710 
2711 			// "If affected by subscript is true, return "subscript"."
2712 			if (affectedBySubscript) {
2713 				return "subscript";
2714 			}
2715 
2716 			// "If affected by superscript is true, return "superscript"."
2717 			if (affectedBySuperscript) {
2718 				return "superscript";
2719 			}
2720 
2721 			// "Return null."
2722 			return null;
2723 		}
2724 
2725 		// "If command is "strikethrough", and the "text-decoration" property of
2726 		// node or any of its ancestors has resolved value containing
2727 		// "line-through", return "line-through". Otherwise, return null."
2728 		if (command == "strikethrough") {
2729 			do {
2730 				if ($_.getComputedStyle(node).textDecoration.indexOf("line-through") != -1) {
2731 					return "line-through";
2732 				}
2733 				node = node.parentNode;
2734 			} while (node && node.nodeType == $_.Node.ELEMENT_NODE);
2735 			return null;
2736 		}
2737 
2738 		// "If command is "underline", and the "text-decoration" property of node
2739 		// or any of its ancestors has resolved value containing "underline",
2740 		// return "underline". Otherwise, return null."
2741 		if (command == "underline") {
2742 			do {
2743 				if ($_.getComputedStyle(node).textDecoration.indexOf("underline") != -1) {
2744 					return "underline";
2745 				}
2746 				node = node.parentNode;
2747 			} while (node && node.nodeType == $_.Node.ELEMENT_NODE);
2748 			return null;
2749 		}
2750 
2751 		if (!commands[command].hasOwnProperty("relevantCssProperty")) {
2752 			throw "Bug: no relevantCssProperty for " + command + " in getEffectiveCommandValue";
2753 		}
2754 
2755 		// "Return the resolved value for node of the relevant CSS property for
2756 		// command."
2757 		return $_.getComputedStyle(node)[commands[command].relevantCssProperty].toString();
2758 	}
2759 
2760 	function getSpecifiedCommandValue(element, command) {
2761 		// "If command is "backColor" or "hiliteColor" and element's display
2762 		// property does not have resolved value "inline", return null."
2763 		if ((command == "backcolor" || command == "hilitecolor") && $_.getComputedStyle(element).display != "inline") {
2764 			return null;
2765 		}
2766 
2767 		// "If command is "createLink" or "unlink":"
2768 		if (command == "createlink" || command == "unlink") {
2769 			// "If element is an a element and has an href attribute, return the
2770 			// value of that attribute."
2771 			if (isAnyHtmlElement(element) && element.tagName == "A" && hasAttribute(element, "href")) {
2772 				return element.getAttribute("href");
2773 			}
2774 
2775 			// "Return null."
2776 			return null;
2777 		}
2778 
2779 		// "If command is "subscript" or "superscript":"
2780 		if (command == "subscript" || command == "superscript") {
2781 			// "If element is a sup, return "superscript"."
2782 			if (isNamedHtmlElement(element, 'sup')) {
2783 				return "superscript";
2784 			}
2785 
2786 			// "If element is a sub, return "subscript"."
2787 			if (isNamedHtmlElement(element, 'sub')) {
2788 				return "subscript";
2789 			}
2790 
2791 			// "Return null."
2792 			return null;
2793 		}
2794 
2795 		// "If command is "strikethrough", and element has a style attribute set,
2796 		// and that attribute sets "text-decoration":"
2797 		if (command == "strikethrough" && element.style.textDecoration != "") {
2798 			// "If element's style attribute sets "text-decoration" to a value
2799 			// containing "line-through", return "line-through"."
2800 			if (element.style.textDecoration.indexOf("line-through") != -1) {
2801 				return "line-through";
2802 			}
2803 
2804 			// "Return null."
2805 			return null;
2806 		}
2807 
2808 		// "If command is "strikethrough" and element is a s or strike element,
2809 		// return "line-through"."
2810 		if (command == "strikethrough" && isHtmlElementInArray(element, ["S", "STRIKE"])) {
2811 			return "line-through";
2812 		}
2813 
2814 		// "If command is "underline", and element has a style attribute set, and
2815 		// that attribute sets "text-decoration":"
2816 		if (command == "underline" && element.style.textDecoration != "") {
2817 			// "If element's style attribute sets "text-decoration" to a value
2818 			// containing "underline", return "underline"."
2819 			if (element.style.textDecoration.indexOf("underline") != -1) {
2820 				return "underline";
2821 			}
2822 
2823 			// "Return null."
2824 			return null;
2825 		}
2826 
2827 		// "If command is "underline" and element is a u element, return
2828 		// "underline"."
2829 		if (command == "underline" && isNamedHtmlElement(element, 'U')) {
2830 			return "underline";
2831 		}
2832 
2833 		// "Let property be the relevant CSS property for command."
2834 		var property = commands[command].relevantCssProperty;
2835 
2836 		// "If property is null, return null."
2837 		if (property === null) {
2838 			return null;
2839 		}
2840 
2841 		// "If element has a style attribute set, and that attribute has the
2842 		// effect of setting property, return the value that it sets property to."
2843 		if (element.style[property] != "") {
2844 			return element.style[property];
2845 		}
2846 
2847 		// "If element is a font element that has an attribute whose effect is
2848 		// to create a presentational hint for property, return the value that the
2849 		// hint sets property to.  (For a size of 7, this will be the non-CSS value
2850 		// "xxx-large".)"
2851 		if (isHtmlNamespace(element.namespaceURI) && element.tagName == "FONT") {
2852 			if (property == "color" && hasAttribute(element, "color")) {
2853 				return element.color;
2854 			}
2855 			if (property == "fontFamily" && hasAttribute(element, "face")) {
2856 				return element.face;
2857 			}
2858 			if (property == "fontSize" && hasAttribute(element, "size")) {
2859 				// This is not even close to correct in general.
2860 				var size = parseInt(element.size, 10);
2861 				if (size < 1) {
2862 					size = 1;
2863 				}
2864 				if (size > 7) {
2865 					size = 7;
2866 				}
2867 				return {
2868 					1: "xx-small",
2869 					2: "small",
2870 					3: "medium",
2871 					4: "large",
2872 					5: "x-large",
2873 					6: "xx-large",
2874 					7: "xxx-large"
2875 				}[size];
2876 			}
2877 		}
2878 
2879 		// "If element is in the following list, and property is equal to the
2880 		// CSS property name listed for it, return the string listed for it."
2881 		//
2882 		// A list follows, whose meaning is copied here.
2883 		if (property == "fontWeight" && (element.tagName == "B" || element.tagName == "STRONG")) {
2884 			return "bold";
2885 		}
2886 		if (property == "fontStyle" && (element.tagName == "I" || element.tagName == "EM")) {
2887 			return "italic";
2888 		}
2889 
2890 		// "Return null."
2891 		return null;
2892 	}
2893 
2894 	function reorderModifiableDescendants(node, command, newValue, range) {
2895 		// "Let candidate equal node."
2896 		var candidate = node;
2897 
2898 		// "While candidate is a modifiable element, and candidate has exactly one
2899 		// child, and that child is also a modifiable element, and candidate is not
2900 		// a simple modifiable element or candidate's specified command value for
2901 		// command is not equivalent to new value, set candidate to its child."
2902 		while (isModifiableElement(candidate) && candidate.childNodes.length == 1 && isModifiableElement(candidate.firstChild) && (!isSimpleModifiableElement(candidate) || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue))) {
2903 			candidate = candidate.firstChild;
2904 		}
2905 
2906 		// "If candidate is node, or is not a simple modifiable element, or its
2907 		// specified command value is not equivalent to new value, or its effective
2908 		// command value is not loosely equivalent to new value, abort these
2909 		// steps."
2910 		if (candidate == node || !isSimpleModifiableElement(candidate) || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue) || !areLooselyEquivalentValues(command, getEffectiveCommandValue(candidate, command), newValue)) {
2911 			return;
2912 		}
2913 
2914 		// "While candidate has children, insert the first child of candidate into
2915 		// candidate's parent immediately before candidate, preserving ranges."
2916 		while (candidate.hasChildNodes()) {
2917 			movePreservingRanges(candidate.firstChild, candidate.parentNode, Dom.getIndexInParent(candidate), range);
2918 		}
2919 
2920 		// "Insert candidate into node's parent immediately after node."
2921 		node.parentNode.insertBefore(candidate, node.nextSibling);
2922 
2923 		// "Append the node as the last child of candidate, preserving ranges."
2924 		movePreservingRanges(node, candidate, -1, range);
2925 	}
2926 
2927 	var recordValuesCommands = ["subscript", "bold", "fontname", "fontsize", "forecolor", "hilitecolor", "italic", "strikethrough", "underline"];
2928 
2929 	function recordValues(nodeList) {
2930 		// "Let values be a list of (node, command, specified command value)
2931 		// triples, initially empty."
2932 		var values = [];
2933 
2934 		// "For each node in node list, for each command in the list "subscript",
2935 		// "bold", "fontName", "fontSize", "foreColor", "hiliteColor", "italic",
2936 		// "strikethrough", and "underline" in that order:"
2937 
2938 		// Ensure we have a plain array to avoid the potential performance
2939 		// overhead of a NodeList
2940 		var nodes = jQuery.makeArray(nodeList);
2941 		var i, j;
2942 		var node;
2943 		var command;
2944 		var ancestor;
2945 		var specifiedCommandValue;
2946 		for (i = 0; i < nodes.length; i++) {
2947 			node = nodes[i];
2948 			for (j = 0; j < recordValuesCommands.length; j++) {
2949 				command = recordValuesCommands[j];
2950 
2951 				// "Let ancestor equal node."
2952 				ancestor = node;
2953 
2954 				// "If ancestor is not an Element, set it to its parent."
2955 				if (ancestor.nodeType != 1) {
2956 					ancestor = ancestor.parentNode;
2957 				}
2958 
2959 				// "While ancestor is an Element and its specified command value
2960 				// for command is null, set it to its parent."
2961 				specifiedCommandValue = null;
2962 				while (ancestor && ancestor.nodeType == 1 && (specifiedCommandValue = getSpecifiedCommandValue(ancestor, command)) === null) {
2963 					ancestor = ancestor.parentNode;
2964 				}
2965 
2966 				// "If ancestor is an Element, add (node, command, ancestor's
2967 				// specified command value for command) to values. Otherwise add
2968 				// (node, command, null) to values."
2969 				values.push([node, command, specifiedCommandValue]);
2970 			}
2971 		}
2972 
2973 		// "Return values."
2974 		return values;
2975 	}
2976 
2977 	//@}
2978 	///// Clearing an element's value /////
2979 	//@{
2980 
2981 	function clearValue(element, command, range) {
2982 		// "If element is not editable, return the empty list."
2983 		if (!isEditable(element)) {
2984 			return [];
2985 		}
2986 
2987 		// "If element's specified command value for command is null, return the
2988 		// empty list."
2989 		if (getSpecifiedCommandValue(element, command) === null) {
2990 			return [];
2991 		}
2992 
2993 		// "If element is a simple modifiable element:"
2994 		if (isSimpleModifiableElement(element)) {
2995 			// "Let children be the children of element."
2996 			var children = Array.prototype.slice.call(toArray(element.childNodes));
2997 
2998 			// "For each child in children, insert child into element's parent
2999 			// immediately before element, preserving ranges."
3000 			var i;
3001 			for (i = 0; i < children.length; i++) {
3002 				movePreservingRanges(children[i], element.parentNode, Dom.getIndexInParent(element), range);
3003 			}
3004 
3005 			// "Remove element from its parent."
3006 			element.parentNode.removeChild(element);
3007 
3008 			// "Return children."
3009 			return children;
3010 		}
3011 
3012 		// "If command is "strikethrough", and element has a style attribute that
3013 		// sets "text-decoration" to some value containing "line-through", delete
3014 		// "line-through" from the value."
3015 		if (command == "strikethrough" && element.style.textDecoration.indexOf("line-through") != -1) {
3016 			if (element.style.textDecoration == "line-through") {
3017 				element.style.textDecoration = "";
3018 			} else {
3019 				element.style.textDecoration = element.style.textDecoration.replace("line-through", "");
3020 			}
3021 			if (element.getAttribute("style") == "") {
3022 				element.removeAttribute("style");
3023 			}
3024 		}
3025 
3026 		// "If command is "underline", and element has a style attribute that sets
3027 		// "text-decoration" to some value containing "underline", delete
3028 		// "underline" from the value."
3029 		if (command == "underline" && element.style.textDecoration.indexOf("underline") != -1) {
3030 			if (element.style.textDecoration == "underline") {
3031 				element.style.textDecoration = "";
3032 			} else {
3033 				element.style.textDecoration = element.style.textDecoration.replace("underline", "");
3034 			}
3035 			if (element.getAttribute("style") == "") {
3036 				element.removeAttribute("style");
3037 			}
3038 		}
3039 
3040 		// "If the relevant CSS property for command is not null, unset the CSS
3041 		// property property of element."
3042 		if (commands[command].relevantCssProperty !== null) {
3043 			element.style[commands[command].relevantCssProperty] = '';
3044 			if (element.getAttribute("style") == "") {
3045 				element.removeAttribute("style");
3046 			}
3047 		}
3048 
3049 		// "If element is a font element:"
3050 		if (isHtmlNamespace(element.namespaceURI) && element.tagName == "FONT") {
3051 			// "If command is "foreColor", unset element's color attribute, if set."
3052 			if (command == "forecolor") {
3053 				element.removeAttribute("color");
3054 			}
3055 
3056 			// "If command is "fontName", unset element's face attribute, if set."
3057 			if (command == "fontname") {
3058 				element.removeAttribute("face");
3059 			}
3060 
3061 			// "If command is "fontSize", unset element's size attribute, if set."
3062 			if (command == "fontsize") {
3063 				element.removeAttribute("size");
3064 			}
3065 		}
3066 
3067 		// "If element is an a element and command is "createLink" or "unlink",
3068 		// unset the href property of element."
3069 		if (isNamedHtmlElement(element, 'A') && (command == "createlink" || command == "unlink")) {
3070 			element.removeAttribute("href");
3071 		}
3072 
3073 		// "If element's specified command value for command is null, return the
3074 		// empty list."
3075 		if (getSpecifiedCommandValue(element, command) === null) {
3076 			return [];
3077 		}
3078 
3079 		// "Set the tag name of element to "span", and return the one-node list
3080 		// consisting of the result."
3081 		return [setTagName(element, "span", range)];
3082 	}
3083 
3084 	//@}
3085 	///// Forcing the value of a node /////
3086 	//@{
3087 
3088 	function forceValue(node, command, newValue, range) {
3089 		var children = [];
3090 		var i;
3091 		var specifiedValue;
3092 
3093 		// "If node's parent is null, abort this algorithm."
3094 		if (!node.parentNode) {
3095 			return;
3096 		}
3097 
3098 		// "If new value is null, abort this algorithm."
3099 		if (newValue === null) {
3100 			return;
3101 		}
3102 
3103 		// "If node is an allowed child of "span":"
3104 		if (isAllowedChild(node, "span")) {
3105 			// "Reorder modifiable descendants of node's previousSibling."
3106 			reorderModifiableDescendants(node.previousSibling, command, newValue, range);
3107 
3108 			// "Reorder modifiable descendants of node's nextSibling."
3109 			reorderModifiableDescendants(node.nextSibling, command, newValue, range);
3110 
3111 			// "Wrap the one-node list consisting of node, with sibling criteria
3112 			// returning true for a simple modifiable element whose specified
3113 			// command value is equivalent to new value and whose effective command
3114 			// value is loosely equivalent to new value and false otherwise, and
3115 			// with new parent instructions returning null."
3116 			wrap(
3117 				[node],
3118 				function (node) {
3119 					return isSimpleModifiableElement(node) && areEquivalentValues(command, getSpecifiedCommandValue(node, command), newValue) && areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue);
3120 				},
3121 				function () {
3122 					return null;
3123 				},
3124 				range
3125 			);
3126 		}
3127 
3128 		// "If the effective command value of command is loosely equivalent to new
3129 		// value on node, abort this algorithm."
3130 		if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) {
3131 			return;
3132 		}
3133 
3134 		// "If node is not an allowed child of "span":"
3135 		if (!isAllowedChild(node, "span")) {
3136 			// "Let children be all children of node, omitting any that are
3137 			// Elements whose specified command value for command is neither null
3138 			// nor equivalent to new value."
3139 			for (i = 0; i < node.childNodes.length; i++) {
3140 				if (node.childNodes[i].nodeType == $_.Node.ELEMENT_NODE) {
3141 					specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command);
3142 
3143 					if (specifiedValue !== null && !areEquivalentValues(command, newValue, specifiedValue)) {
3144 						continue;
3145 					}
3146 				}
3147 				children.push(node.childNodes[i]);
3148 			}
3149 
3150 			// "Force the value of each Node in children, with command and new
3151 			// value as in this invocation of the algorithm."
3152 			for (i = 0; i < children.length; i++) {
3153 				forceValue(children[i], command, newValue, range);
3154 			}
3155 
3156 			// "Abort this algorithm."
3157 			return;
3158 		}
3159 
3160 		// "If the effective command value of command is loosely equivalent to new
3161 		// value on node, abort this algorithm."
3162 		if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) {
3163 			return;
3164 		}
3165 
3166 		// "Let new parent be null."
3167 		var newParent = null;
3168 
3169 		// "If the CSS styling flag is false:"
3170 		if (!cssStylingFlag) {
3171 			// "If command is "bold" and new value is "bold", let new parent be the
3172 			// result of calling createElement("b") on the ownerDocument of node."
3173 			if (command == "bold" && (newValue == "bold" || newValue == "700")) {
3174 				newParent = node.ownerDocument.createElement("b");
3175 			}
3176 
3177 			// "If command is "italic" and new value is "italic", let new parent be
3178 			// the result of calling createElement("i") on the ownerDocument of
3179 			// node."
3180 			if (command == "italic" && newValue == "italic") {
3181 				newParent = node.ownerDocument.createElement("i");
3182 			}
3183 
3184 			// "If command is "strikethrough" and new value is "line-through", let
3185 			// new parent be the result of calling createElement("s") on the
3186 			// ownerDocument of node."
3187 			if (command == "strikethrough" && newValue == "line-through") {
3188 				newParent = node.ownerDocument.createElement("s");
3189 			}
3190 
3191 			// "If command is "underline" and new value is "underline", let new
3192 			// parent be the result of calling createElement("u") on the
3193 			// ownerDocument of node."
3194 			if (command == "underline" && newValue == "underline") {
3195 				newParent = node.ownerDocument.createElement("u");
3196 			}
3197 
3198 			// "If command is "foreColor", and new value is fully opaque with red,
3199 			// green, and blue components in the range 0 to 255:"
3200 			if (command == "forecolor" && parseSimpleColor(newValue)) {
3201 				// "Let new parent be the result of calling createElement("span")
3202 				// on the ownerDocument of node."
3203 				// NOTE: modified this process to create span elements with style attributes
3204 				// instead of oldschool font tags with color attributes
3205 				newParent = node.ownerDocument.createElement("span");
3206 
3207 				// "If new value is an extended color keyword, set the color
3208 				// attribute of new parent to new value."
3209 				//
3210 				// "Otherwise, set the color attribute of new parent to the result
3211 				// of applying the rules for serializing simple color values to new
3212 				// value (interpreted as a simple color)."
3213 				jQuery(newParent).css('color', parseSimpleColor(newValue));
3214 			}
3215 
3216 			// "If command is "fontName", let new parent be the result of calling
3217 			// createElement("font") on the ownerDocument of node, then set the
3218 			// face attribute of new parent to new value."
3219 			if (command == "fontname") {
3220 				newParent = node.ownerDocument.createElement("font");
3221 				newParent.face = newValue;
3222 			}
3223 		}
3224 
3225 		// "If command is "createLink" or "unlink":"
3226 		if (command == "createlink" || command == "unlink") {
3227 			// "Let new parent be the result of calling createElement("a") on the
3228 			// ownerDocument of node."
3229 			newParent = node.ownerDocument.createElement("a");
3230 
3231 			// "Set the href attribute of new parent to new value."
3232 			newParent.setAttribute("href", newValue);
3233 
3234 			// "Let ancestor be node's parent."
3235 			var ancestor = node.parentNode;
3236 
3237 			// "While ancestor is not null:"
3238 			while (ancestor) {
3239 				// "If ancestor is an a, set the tag name of ancestor to "span",
3240 				// and let ancestor be the result."
3241 				if (isNamedHtmlElement(ancestor, 'A')) {
3242 					ancestor = setTagName(ancestor, "span", range);
3243 				}
3244 
3245 				// "Set ancestor to its parent."
3246 				ancestor = ancestor.parentNode;
3247 			}
3248 		}
3249 
3250 		// "If command is "fontSize"; and new value is one of "xx-small", "small",
3251 		// "medium", "large", "x-large", "xx-large", or "xxx-large"; and either the
3252 		// CSS styling flag is false, or new value is "xxx-large": let new parent
3253 		// be the result of calling createElement("font") on the ownerDocument of
3254 		// node, then set the size attribute of new parent to the number from the
3255 		// following table based on new value: [table omitted]"
3256 		if (command == "fontsize" && jQuery.inArray(newValue, ["xx-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) != -1 && (!cssStylingFlag || newValue == "xxx-large")) {
3257 			newParent = node.ownerDocument.createElement("font");
3258 			newParent.size = cssSizeToLegacy(newValue);
3259 		}
3260 
3261 		// "If command is "subscript" or "superscript" and new value is
3262 		// "subscript", let new parent be the result of calling
3263 		// createElement("sub") on the ownerDocument of node."
3264 		if ((command == "subscript" || command == "superscript") && newValue == "subscript") {
3265 			newParent = node.ownerDocument.createElement("sub");
3266 		}
3267 
3268 		// "If command is "subscript" or "superscript" and new value is
3269 		// "superscript", let new parent be the result of calling
3270 		// createElement("sup") on the ownerDocument of node."
3271 		if ((command == "subscript" || command == "superscript") && newValue == "superscript") {
3272 			newParent = node.ownerDocument.createElement("sup");
3273 		}
3274 
3275 		// "If new parent is null, let new parent be the result of calling
3276 		// createElement("span") on the ownerDocument of node."
3277 		if (!newParent) {
3278 			newParent = node.ownerDocument.createElement("span");
3279 		}
3280 
3281 		// "Insert new parent in node's parent before node."
3282 		node.parentNode.insertBefore(newParent, node);
3283 
3284 		// "If the effective command value of command for new parent is not loosely
3285 		// equivalent to new value, and the relevant CSS property for command is
3286 		// not null, set that CSS property of new parent to new value (if the new
3287 		// value would be valid)."
3288 		var property = commands[command].relevantCssProperty;
3289 		if (property !== null && !areLooselyEquivalentValues(command, getEffectiveCommandValue(newParent, command), newValue)) {
3290 			newParent.style[property] = newValue;
3291 		}
3292 
3293 		// "If command is "strikethrough", and new value is "line-through", and the
3294 		// effective command value of "strikethrough" for new parent is not
3295 		// "line-through", set the "text-decoration" property of new parent to
3296 		// "line-through"."
3297 		if (command == "strikethrough" && newValue == "line-through" && getEffectiveCommandValue(newParent, "strikethrough") != "line-through") {
3298 			newParent.style.textDecoration = "line-through";
3299 		}
3300 
3301 		// "If command is "underline", and new value is "underline", and the
3302 		// effective command value of "underline" for new parent is not
3303 		// "underline", set the "text-decoration" property of new parent to
3304 		// "underline"."
3305 		if (command == "underline" && newValue == "underline" && getEffectiveCommandValue(newParent, "underline") != "underline") {
3306 			newParent.style.textDecoration = "underline";
3307 		}
3308 
3309 		// "Append node to new parent as its last child, preserving ranges."
3310 		movePreservingRanges(node, newParent, newParent.childNodes.length, range);
3311 
3312 		// "If node is an Element and the effective command value of command for
3313 		// node is not loosely equivalent to new value:"
3314 		if (node.nodeType == $_.Node.ELEMENT_NODE && !areEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) {
3315 			// "Insert node into the parent of new parent before new parent,
3316 			// preserving ranges."
3317 			movePreservingRanges(node, newParent.parentNode, Dom.getIndexInParent(newParent), range);
3318 
3319 			// "Remove new parent from its parent."
3320 			newParent.parentNode.removeChild(newParent);
3321 
3322 			// "Let children be all children of node, omitting any that are
3323 			// Elements whose specified command value for command is neither null
3324 			// nor equivalent to new value."
3325 			children = [];
3326 			for (i = 0; i < node.childNodes.length; i++) {
3327 				if (node.childNodes[i].nodeType == $_.Node.ELEMENT_NODE) {
3328 					specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command);
3329 
3330 					if (specifiedValue !== null && !areEquivalentValues(command, newValue, specifiedValue)) {
3331 						continue;
3332 					}
3333 				}
3334 				children.push(node.childNodes[i]);
3335 			}
3336 
3337 			// "Force the value of each Node in children, with command and new
3338 			// value as in this invocation of the algorithm."
3339 			for (i = 0; i < children.length; i++) {
3340 				forceValue(children[i], command, newValue, range);
3341 			}
3342 		}
3343 	}
3344 
3345 	//@}
3346 	///// Pushing down values /////
3347 	//@{
3348 
3349 	function pushDownValues(node, command, newValue, range) {
3350 		// "If node's parent is not an Element, abort this algorithm."
3351 		if (!node.parentNode || node.parentNode.nodeType != $_.Node.ELEMENT_NODE) {
3352 			return;
3353 		}
3354 
3355 		// "If the effective command value of command is loosely equivalent to new
3356 		// value on node, abort this algorithm."
3357 		if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) {
3358 			return;
3359 		}
3360 
3361 		// "Let current ancestor be node's parent."
3362 		var currentAncestor = node.parentNode;
3363 
3364 		// "Let ancestor list be a list of Nodes, initially empty."
3365 		var ancestorList = [];
3366 3367 
		// "While current ancestor is an editable Element and the effective command
3368 		// value of command is not loosely equivalent to new value on it, append
3369 		// current ancestor to ancestor list, then set current ancestor to its
3370 		// parent."
3371 		while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !areLooselyEquivalentValues(command, getEffectiveCommandValue(currentAncestor, command), newValue)) {
3372 			ancestorList.push(currentAncestor);
3373 			currentAncestor = currentAncestor.parentNode;
3374 		}
3375 
3376 		// "If ancestor list is empty, abort this algorithm."
3377 		if (!ancestorList.length) {
3378 			return;
3379 		}
3380 
3381 		// "Let propagated value be the specified command value of command on the
3382 		// last member of ancestor list."
3383 		var propagatedValue = getSpecifiedCommandValue(ancestorList[ancestorList.length - 1], command);
3384 
3385 		// "If propagated value is null and is not equal to new value, abort this
3386 		// algorithm."
3387 		if (propagatedValue === null && propagatedValue != newValue) {
3388 			return;
3389 		}
3390 
3391 		// "If the effective command value for the parent of the last member of
3392 		// ancestor list is not loosely equivalent to new value, and new value is
3393 		// not null, abort this algorithm."
3394 		if (newValue !== null && !areLooselyEquivalentValues(command, getEffectiveCommandValue(ancestorList[ancestorList.length - 1].parentNode, command), newValue)) {
3395 			return;
3396 		}
3397 
3398 		// "While ancestor list is not empty:"
3399 		while (ancestorList.length) {
3400 			// "Let current ancestor be the last member of ancestor list."
3401 			// "Remove the last member from ancestor list."
3402 			currentAncestor = ancestorList.pop();
3403 
3404 			// "If the specified command value of current ancestor for command is
3405 			// not null, set propagated value to that value."
3406 			if (getSpecifiedCommandValue(currentAncestor, command) !== null) {
3407 				propagatedValue = getSpecifiedCommandValue(currentAncestor, command);
3408 			}
3409 
3410 			// "Let children be the children of current ancestor."
3411 			var children = Array.prototype.slice.call(toArray(currentAncestor.childNodes));
3412 
3413 			// "If the specified command value of current ancestor for command is
3414 			// not null, clear the value of current ancestor."
3415 			if (getSpecifiedCommandValue(currentAncestor, command) !== null) {
3416 				clearValue(currentAncestor, command, range);
3417 			}
3418 
3419 			// "For every child in children:"
3420 3421 			var i;
3422 			for (i = 0; i < children.length; i++) {
3423 				var child = children[i];
3424 
3425 				// "If child is node, continue with the next child."
3426 				if (child == node) {
3427 					continue;
3428 				}
3429 
3430 				// "If child is an Element whose specified command value for
3431 				// command is neither null nor equivalent to propagated value,
3432 				// continue with the next child."
3433 				if (child.nodeType == $_.Node.ELEMENT_NODE && getSpecifiedCommandValue(child, command) !== null && !areEquivalentValues(command, propagatedValue, getSpecifiedCommandValue(child, command))) {
3434 					continue;
3435 				}
3436 
3437 				// "If child is the last member of ancestor list, continue with the
3438 				// next child."
3439 				if (child == ancestorList[ancestorList.length - 1]) {
3440 					continue;
3441 				}
3442 
3443 				// "Force the value of child, with command as in this algorithm
3444 				// and new value equal to propagated value."
3445 				forceValue(child, command, propagatedValue, range);
3446 			}
3447 		}
3448 	}
3449 
3450 	function restoreValues(values, range) {
3451 		// "For each (node, command, value) triple in values:"
3452 		$_(values).forEach(function (triple) {
3453 			var node = triple[0];
3454 			var command = triple[1];
3455 			var value = triple[2];
3456 
3457 			// "Let ancestor equal node."
3458 			var ancestor = node;
3459 
3460 			// "If ancestor is not an Element, set it to its parent."
3461 			if (!ancestor || ancestor.nodeType != $_.Node.ELEMENT_NODE) {
3462 				ancestor = ancestor.parentNode;
3463 			}
3464 
3465 			// "While ancestor is an Element and its specified command value for
3466 			// command is null, set it to its parent."
3467 			while (ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE && getSpecifiedCommandValue(ancestor, command) === null) {
3468 				ancestor = ancestor.parentNode;
3469 			}
3470 
3471 			// "If value is null and ancestor is an Element, push down values on
3472 			// node for command, with new value null."
3473 			if (value === null && ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE) {
3474 				pushDownValues(node, command, null, range);
3475 
3476 				// "Otherwise, if ancestor is an Element and its specified command
3477 				// value for command is not equivalent to value, or if ancestor is not
3478 				// an Element and value is not null, force the value of command to
3479 				// value on node."
3480 			} else if ((ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE && !areEquivalentValues(command, getSpecifiedCommandValue(ancestor, command), value)) || ((!ancestor || ancestor.nodeType != $_.Node.ELEMENT_NODE) && value !== null)) {
3481 				forceValue(node, command, value, range);
3482 			}
3483 		});
3484 	}
3485 
3486 	//@}
3487 	///// Setting the selection's value /////
3488 	//@{
3489 
3490 	function setSelectionValue(command, newValue, range) {
3491 
3492 		// Use current selected range if no range passed
3493 		range = range || getActiveRange();
3494 
3495 		// "If there is no editable text node effectively contained in the active
3496 		// range:"
3497 		if (!$_(getAllEffectivelyContainedNodes(range)).filter(function (node) { return node.nodeType == $_.Node.TEXT_NODE; }, true).some(isEditable)) {
3498 			// "If command has inline command activated values, set the state
3499 			// override to true if new value is among them and false if it's not."
3500 			if (commands[command].hasOwnProperty("inlineCommandActivatedValues")) {
3501 				setStateOverride(
3502 					command,
3503 					$_(commands[command].inlineCommandActivatedValues).indexOf(newValue) != -1,
3504 					range
3505 				);
3506 			}
3507 
3508 			// "If command is "subscript", unset the state override for
3509 			// "superscript"."
3510 			if (command == "subscript") {
3511 				unsetStateOverride("superscript", range);
3512 			}
3513 
3514 			// "If command is "superscript", unset the state override for
3515 3516 			// "subscript"."
3517 			if (command == "superscript") {
3518 				unsetStateOverride("subscript", range);
3519 			}
3520 
3521 			// "If new value is null, unset the value override (if any)."
3522 			if (newValue === null) {
3523 				unsetValueOverride(command, range);
3524 
3525 				// "Otherwise, if command has a value specified, set the value override
3526 				// to new value."
3527 			} else if (commands[command].hasOwnProperty("value")) {
3528 				setValueOverride(command, newValue, range);
3529 			}
3530 
3531 			// "Abort these steps."
3532 			return;
3533 		}
3534 
3535 		// "If the active range's start node is an editable Text node, and its
3536 		// start offset is neither zero nor its start node's length, call
3537 		// splitText() on the active range's start node, with argument equal to the
3538 		// active range's start offset. Then set the active range's start node to
3539 		// the result, and its start offset to zero."
3540 		if (isEditable(range.startContainer) && range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset != 0 && range.startOffset != getNodeLength(range.startContainer)) {
3541 			// Account for browsers not following range mutation rules
3542 			var newNode = splitText(range.startContainer, range.startOffset);
3543 			var newActiveRange = Aloha.createRange();
3544 			if (range.startContainer == range.endContainer) {
3545 				var newEndOffset = range.endOffset - range.startOffset;
3546 				newActiveRange.setEnd(newNode, newEndOffset);
3547 				range.setEnd(newNode, newEndOffset);
3548 			}
3549 			newActiveRange.setStart(newNode, 0);
3550 			Aloha.getSelection().removeAllRanges();
3551 			Aloha.getSelection().addRange(newActiveRange);
3552 
3553 			range.setStart(newNode, 0);
3554 		}
3555 
3556 		// "If the active range's end node is an editable Text node, and its end
3557 		// offset is neither zero nor its end node's length, call splitText() on
3558 		// the active range's end node, with argument equal to the active range's
3559 		// end offset."
3560 		if (isEditable(range.endContainer) && range.endContainer.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0 && range.endOffset != getNodeLength(range.endContainer)) {
3561 			// IE seems to mutate the range incorrectly here, so we need correction
3562 			// here as well.  The active range will be temporarily in orphaned
3563 			// nodes, so calling getActiveRange() after splitText() but before
3564 			// fixing the range will throw an exception.
3565 			// TODO: check if this is still neccessary
3566 			var activeRange = range;
3567 			var newStart = [activeRange.startContainer, activeRange.startOffset];
3568 			var newEnd = [activeRange.endContainer, activeRange.endOffset];
3569 			splitText(activeRange.endContainer, activeRange.endOffset);
3570 			activeRange.setStart(newStart[0], newStart[1]);
3571 			activeRange.setEnd(newEnd[0], newEnd[1]);
3572 
3573 			Aloha.getSelection().removeAllRanges();
3574 			Aloha.getSelection().addRange(activeRange);
3575 		}
3576 
3577 		// "Let element list be all editable Elements effectively contained in the
3578 		// active range.
3579 		//
3580 		// "For each element in element list, clear the value of element."
3581 		$_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) {
3582 			return isEditable(node) && node.nodeType == $_.Node.ELEMENT_NODE;
3583 		})).forEach(function (element) {
3584 			clearValue(element, command, range);
3585 		});
3586 
3587 		// "Let node list be all editable nodes effectively contained in the active
3588 		// range.
3589 		//
3590 		// "For each node in node list:"
3591 		$_(getAllEffectivelyContainedNodes(range, isEditable)).forEach(function (node) {
3592 			// "Push down values on node."
3593 			pushDownValues(node, command, newValue, range);
3594 
3595 			// "Force the value of node."
3596 			forceValue(node, command, newValue, range);
3597 		});
3598 	}
3599 
3600 	/**
3601 	 * attempt to retrieve a block like a table or an Aloha Block
3602 	 * which is located one step right of the current caret position.
3603 	 * If an appropriate element is found it will be returned or
3604 	 * false otherwise
3605 	 *
3606 	 * @param {element} node current node we're in
3607 	 * @param {number} offset current offset within that node
3608 	 *
3609 	 * @return the dom node if found or false if no appropriate
3610 	 * element was found
3611 	 */
3612 	function getBlockAtNextPosition(node, offset) {
3613 		var i;
3614 
3615 		// if we're inside a text node we first have to check
3616 		// if there is nothing but tabs, newlines or the like
3617 		// after our current cursor position
3618 		if (node.nodeType === $_.Node.TEXT_NODE && offset < node.length) {
3619 			for (i = offset; i < node.length; i++) {
3620 				if ((node.data.charAt(i) !== '\t' && node.data.charAt(i) !== '\r' && node.data.charAt(i) !== '\n') || node.data.charCodeAt(i) === 160) { //  
3621 					// this is a character that has to be deleted first
3622 					return false;
3623 				}
3624 			}
3625 		}
3626 
3627 		// try the most simple approach first: the next sibling
3628 		// is a table
3629 		if (node.nextSibling && node.nextSibling.className && node.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) {
3630 			return node.nextSibling;
3631 		}
3632 
3633 		// since we got only ignorable whitespace here determine if
3634 		// our nodes parents next sibling is a table
3635 		if (node.parentNode && node.parentNode.nextSibling && node.parentNode.nextSibling.className && node.parentNode.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) {
3636 			return node.parentNode.nextSibling;
3637 		}
3638 
3639 		// our parents nextsibling is a pure whitespace node such as
3640 		// generated by sourcecode indentation so we'll check for
3641 		// the next next sibling
3642 		if (node.parentNode && node.parentNode.nextSibling && isWhitespaceNode(node.parentNode.nextSibling) && node.parentNode.nextSibling.nextSibling && node.parentNode.nextSibling.nextSibling.className && node.parentNode.nextSibling.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) {
3643 			return node.parentNode.nextSibling.nextSibling;
3644 		}
3645 
3646 		// Note: the search above works for tables, since they cannot be
3647 		// nested deeply in paragraphs and other formatting tags. If this code
3648 		// is extended to work also for other blocks, the search probably needs to be adapted
3649 	}
3650 
3651 	/**
3652 	 * Attempt to retrieve a block like a table or an Aloha Block
3653 	 * which is located right before the current position.
3654 	 * If an appropriate element is found, it will be returned or
3655 	 * false otherwise
3656 	 *
3657 	 * @param {element} node current node
3658 	 * @param {offset} offset current offset
3659 	 *
3660 	 * @return dom node of found or false if no appropriate
3661 	 * element was found
3662 	 */
3663 	function getBlockAtPreviousPosition(node, offset) {
3664 		var i;
3665 
3666 		if (node.nodeType === $_.Node.TEXT_NODE && offset > 0) {
3667 			for (i = offset - 1; i >= 0; i--) {
3668 				if ((node.data.charAt(i) !== '\t' && node.data.charAt(i) !== '\r' && node.data.charAt(i) !== '\n') || node.data.charCodeAt(i) === 160) { //  
3669 					// this is a character that has to be deleted first
3670 					return false;
3671 				}
3672 			}
3673 		}
3674 
3675 		// try the previous sibling
3676 		if (node.previousSibling && node.previousSibling.className && node.previousSibling.className.indexOf("aloha-table-wrapper") >= 0) {
3677 			return node.previousSibling;
3678 		}
3679 
3680 		// try the parent's previous sibling
3681 		if (node.parentNode && node.parentNode.previousSibling && node.parentNode.previousSibling.className && node.parentNode.previousSibling.className.indexOf("aloha-table-wrapper") >= 0) {
3682 			return node.parentNode.previousSibling;
3683 		}
3684 
3685 		// the parent's previous sibling might be a whitespace node
3686 		if (node.parentNode && node.parentNode.previousSibling && isWhitespaceNode(node.parentNode.previousSibling) && node.parentNode.previousSibling.previousSibling && node.parentNode.previousSibling.previousSibling.className && node.parentNode.previousSibling.previousSibling.className.indexOf('aloha-table-wrapper') >= 0) {
3687 			return node.parentNode.previousSibling.previousSibling;
3688 		}
3689 
3690 		// Note: the search above works for tables, since they cannot be
3691 		// nested deeply in paragraphs and other formatting tags. If this code
3692 		// is extended to work also for other blocks, the search probably needs to be adapted
3693 
3694 		return false;
3695 	}
3696 
3697 	// "A boundary point (node, offset) is a block start point if either node's
3698 	// parent is null and offset is zero; or node has a child with index offset −
3699 	// 1, and that child is either a visible block node or a visible br."
3700 	function isBlockStartPoint(node, offset) {
3701 		return (!node.parentNode && offset == 0) || (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1]) && (isBlockNode(node.childNodes[offset - 1]) || isNamedHtmlElement(node.childNodes[offset - 1], "br")));
3702 	}
3703 
3704 	// "A boundary point (node, offset) is a block end point if either node's
3705 	// parent is null and offset is node's length; or node has a child with index
3706 	// offset, and that child is a visible block node."
3707 	function isBlockEndPoint(node, offset) {
3708 		return (!node.parentNode && offset == getNodeLength(node)) || (offset < node.childNodes.length && isVisible(node.childNodes[offset]) && isBlockNode(node.childNodes[offset]));
3709 	}
3710 
3711 	// "A boundary point is a block boundary point if it is either a block start
3712 	// point or a block end point."
3713 	function isBlockBoundaryPoint(node, offset) {
3714 		return isBlockStartPoint(node, offset) || isBlockEndPoint(node, offset);
3715 	}
3716 
3717 	function followsLineBreak(node) {
3718 		// "Let offset be zero."
3719 		var offset = 0;
3720 
3721 		// "While (node, offset) is not a block boundary point:"
3722 		while (!isBlockBoundaryPoint(node, offset)) {
3723 			// "If node has a visible child with index offset minus one, return
3724 			// false."
3725 			if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1])) {
3726 				return false;
3727 			}
3728 
3729 			// "If offset is zero or node has no children, set offset to node's
3730 			// index, then set node to its parent."
3731 			if (offset == 0 || !node.hasChildNodes()) {
3732 				offset = Dom.getIndexInParent(node);
3733 				node = node.parentNode;
3734 
3735 				// "Otherwise, set node to its child with index offset minus one, then
3736 				// set offset to node's length."
3737 			} else {
3738 				node = node.childNodes[offset - 1];
3739 				offset = getNodeLength(node);
3740 			}
3741 		}
3742 
3743 		// "Return true."
3744 		return true;
3745 	}
3746 
3747 	function precedesLineBreak(node) {
3748 		// "Let offset be node's length."
3749 		var offset = getNodeLength(node);
3750 
3751 3752 		// "While (node, offset) is not a block boundary point:"
3753 		while (!isBlockBoundaryPoint(node, offset)) {
3754 			// "If node has a visible child with index offset, return false."
3755 			if (offset < node.childNodes.length && isVisible(node.childNodes[offset])) {
3756 				return false;
3757 			}
3758 
3759 			// "If offset is node's length or node has no children, set offset to
3760 			// one plus node's index, then set node to its parent."
3761 			if (offset == getNodeLength(node) || !node.hasChildNodes()) {
3762 				offset = 1 + Dom.getIndexInParent(node);
3763 				node = node.parentNode;
3764 
3765 				// "Otherwise, set node to its child with index offset and set offset
3766 				// to zero."
3767 			} else {
3768 				node = node.childNodes[offset];
3769 				offset = 0;
3770 			}
3771 		}
3772 
3773 		// "Return true."
3774 		return true;
3775 	}
3776 
3777 	//@}
3778 	///// Splitting a node list's parent /////
3779 	//@{
3780 
3781 	function splitParent(nodeList, range) {
3782 		var i;
3783 
3784 		// "Let original parent be the parent of the first member of node list."
3785 		var originalParent = nodeList[0].parentNode;
3786 
3787 		// "If original parent is not editable or its parent is null, do nothing
3788 		// and abort these steps."
3789 		if (!isEditable(originalParent) || !originalParent.parentNode) {
3790 			return;
3791 		}
3792 
3793 		// "If the first child of original parent is in node list, remove
3794 		// extraneous line breaks before original parent."
3795 		if (jQuery.inArray(originalParent.firstChild, nodeList) != -1) {
3796 			removeExtraneousLineBreaksBefore(originalParent);
3797 		}
3798 
3799 		var firstChildInNodeList = jQuery.inArray(originalParent.firstChild, nodeList) != -1;
3800 		var lastChildInNodeList = jQuery.inArray(originalParent.lastChild, nodeList) != -1;
3801 
3802 		// "If the first child of original parent is in node list, and original
3803 		// parent follows a line break, set follows line break to true. Otherwise,
3804 		// set follows line break to false."
3805 		var followsLineBreak_ = firstChildInNodeList && followsLineBreak(originalParent);
3806 
3807 		// "If the last child of original parent is in node list, and original
3808 		// parent precedes a line break, set precedes line break to true.
3809 		// Otherwise, set precedes line break to false."
3810 		var precedesLineBreak_ = lastChildInNodeList && precedesLineBreak(originalParent);
3811 
3812 		// "If the first child of original parent is not in node list, but its last
3813 		// child is:"
3814 		if (!firstChildInNodeList && lastChildInNodeList) {
3815 			// "For each node in node list, in reverse order, insert node into the
3816 			// parent of original parent immediately after original parent,
3817 			// preserving ranges."
3818 			for (i = nodeList.length - 1; i >= 0; i--) {
3819 				movePreservingRanges(nodeList[i], originalParent.parentNode, 1 + Dom.getIndexInParent(originalParent), range);
3820 			}
3821 
3822 			// "If precedes line break is true, and the last member of node list
3823 			// does not precede a line break, call createElement("br") on the
3824 			// context object and insert the result immediately after the last
3825 			// member of node list."
3826 			if (precedesLineBreak_ && !precedesLineBreak(nodeList[nodeList.length - 1])) {
3827 				nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling);
3828 			}
3829 
3830 			// "Remove extraneous line breaks at the end of original parent."
3831 			removeExtraneousLineBreaksAtTheEndOf(originalParent);
3832 
3833 			// "Abort these steps."
3834 			return;
3835 		}
3836 
3837 		// "If the first child of original parent is not in node list:"
3838 		if (!firstChildInNodeList) {
3839 			// "Let cloned parent be the result of calling cloneNode(false) on
3840 			// original parent."
3841 			var clonedParent = originalParent.cloneNode(false);
3842 
3843 			// "If original parent has an id attribute, unset it."
3844 			originalParent.removeAttribute("id");
3845 
3846 			// "Insert cloned parent into the parent of original parent immediately
3847 			// before original parent."
3848 			originalParent.parentNode.insertBefore(clonedParent, originalParent);
3849 
3850 			// "While the previousSibling of the first member of node list is not
3851 			// null, append the first child of original parent as the last child of
3852 			// cloned parent, preserving ranges."
3853 			while (nodeList[0].previousSibling) {
3854 				movePreservingRanges(originalParent.firstChild, clonedParent, clonedParent.childNodes.length, range);
3855 			}
3856 		}
3857 
3858 		// "For each node in node list, insert node into the parent of original
3859 		// parent immediately before original parent, preserving ranges."
3860 		for (i = 0; i < nodeList.length; i++) {
3861 			movePreservingRanges(nodeList[i], originalParent.parentNode, Dom.getIndexInParent(originalParent), range);
3862 		}
3863 
3864 		// "If follows line break is true, and the first member of node list does
3865 		// not follow a line break, call createElement("br") on the context object
3866 		// and insert the result immediately before the first member of node list."
3867 		if (followsLineBreak_ && !followsLineBreak(nodeList[0])) {
3868 			nodeList[0].parentNode.insertBefore(document.createElement("br"), nodeList[0]);
3869 		}
3870 
3871 		// "If the last member of node list is an inline node other than a br, and
3872 		// the first child of original parent is a br, and original parent is not
3873 		// an inline node, remove the first child of original parent from original
3874 		// parent."
3875 		if (isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "br") && isNamedHtmlElement(originalParent.firstChild, "br") && !isInlineNode(originalParent)) {
3876 			originalParent.removeChild(originalParent.firstChild);
3877 		}
3878 
3879 		// "If original parent has no children:"
3880 		if (!originalParent.hasChildNodes()) {
3881 			// if the current range is collapsed and at the end of the originalParent.parentNode
3882 			// the offset will not be available anymore after the next step (remove child)
3883 			// that's why we need to fix the range to prevent a bogus offset
3884 			if (originalParent.parentNode === range.startContainer && originalParent.parentNode === range.endContainer && range.startContainer === range.endContainer && range.startOffset === range.endOffset && originalParent.parentNode.childNodes.length === range.startOffset) {
3885 				range.startOffset = originalParent.parentNode.childNodes.length - 1;
3886 				range.endOffset = range.startOffset;
3887 			}
3888 
3889 			// "Remove original parent from its parent."
3890 			originalParent.parentNode.removeChild(originalParent);
3891 
3892 			// "If precedes line break is true, and the last member of node list
3893 			// does not precede a line break, call createElement("br") on the
3894 			// context object and insert the result immediately after the last
3895 			// member of node list."
3896 			if (precedesLineBreak_ && !precedesLineBreak(nodeList[nodeList.length - 1])) {
3897 				nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling);
3898 			}
3899 
3900 			// "Otherwise, remove extraneous line breaks before original parent."
3901 		} else {
3902 			removeExtraneousLineBreaksBefore(originalParent);
3903 		}
3904 
3905 		// "If node list's last member's nextSibling is null, but its parent is not
3906 		// null, remove extraneous line breaks at the end of node list's last
3907 		// member's parent."
3908 		if (!nodeList[nodeList.length - 1].nextSibling && nodeList[nodeList.length - 1].parentNode) {
3909 			removeExtraneousLineBreaksAtTheEndOf(nodeList[nodeList.length - 1].parentNode);
3910 		}
3911 	}
3912 
3913 	//@}
3914 	///// The backColor command /////
3915 	//@{
3916 	commands.backcolor = {
3917 		// Copy-pasted, same as hiliteColor
3918 		action: function (value, range) {
3919 			// Action is further copy-pasted, same as foreColor
3920 
3921 			// "If value is not a valid CSS color, prepend "#" to it."
3922 			//
3923 			// "If value is still not a valid CSS color, or if it is currentColor,
3924 			// abort these steps and do nothing."
3925 			//
3926 			// Cheap hack for testing, no attempt to be comprehensive.
3927 3928 			if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) {
3929 				value = "#" + value;
3930 			}
3931 			if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") {
3932 				return;
3933 			}
3934 
3935 			// "Set the selection's value to value."
3936 			setSelectionValue("backcolor", value, range);
3937 		},
3938 		standardInlineValueCommand: true,
3939 		relevantCssProperty: "backgroundColor",
3940 		equivalentValues: function (val1, val2) {
3941 			// "Either both strings are valid CSS colors and have the same red,
3942 			// green, blue, and alpha components, or neither string is a valid CSS
3943 			// color."
3944 			return normalizeColor(val1) === normalizeColor(val2);
3945 		}
3946 	};
3947 
3948 	//@}
3949 	///// The bold command /////
3950 	//@{
3951 	commands.bold = {
3952 		action: function (value, range) {
3953 			// "If queryCommandState("bold") returns true, set the selection's
3954 			// value to "normal". Otherwise set the selection's value to "bold"."
3955 			if (myQueryCommandState("bold", range)) {
3956 				setSelectionValue("bold", "normal", range);
3957 			} else {
3958 				setSelectionValue("bold", "bold", range);
3959 			}
3960 		},
3961 		inlineCommandActivatedValues: ["bold", "600", "700", "800", "900"],
3962 		relevantCssProperty: "fontWeight",
3963 		equivalentValues: function (val1, val2) {
3964 			// "Either the two strings are equal, or one is "bold" and the other is
3965 			// "700", or one is "normal" and the other is "400"."
3966 			return val1 == val2 || (val1 == "bold" && val2 == "700") || (val1 == "700" && val2 == "bold") || (val1 == "normal" && val2 == "400") || (val1 == "400" && val2 == "normal");
3967 		}
3968 	};
3969 
3970 	//@}
3971 	///// The createLink command /////
3972 	//@{
3973 	commands.createlink = {
3974 		action: function (value, range) {
3975 			// "If value is the empty string, abort these steps and do nothing."
3976 			if (value === "") {
3977 				return;
3978 			}
3979 
3980 			// "For each editable a element that has an href attribute and is an
3981 			// ancestor of some node effectively contained in the active range, set
3982 			// that a element's href attribute to value."
3983 			//
3984 			// TODO: We don't actually do this in tree order, not that it matters
3985 			// unless you're spying with mutation events.
3986 			$_(getAllEffectivelyContainedNodes(getActiveRange())).forEach(function (node) {
3987 				$_(getAncestors(node)).forEach(function (ancestor) {
3988 					if (isEditable(ancestor) && isNamedHtmlElement(ancestor, 'a') && hasAttribute(ancestor, "href")) {
3989 						ancestor.setAttribute("href", value);
3990 					}
3991 				});
3992 			});
3993 
3994 			// "Set the selection's value to value."
3995 			setSelectionValue("createlink", value, range);
3996 		},
3997 		standardInlineValueCommand: true
3998 	};
3999 
4000 	//@}
4001 	///// The fontName command /////
4002 	//@{
4003 	commands.fontname = {
4004 		action: function (value, range) {
4005 			// "Set the selection's value to value."
4006 			setSelectionValue("fontname", value, range);
4007 		},
4008 		standardInlineValueCommand: true,
4009 		relevantCssProperty: "fontFamily"
4010 	};
4011 
4012 	//@}
4013 	///// The fontSize command /////
4014 	//@{
4015 
4016 	commands.fontsize = {
4017 		action: function (value, range) {
4018 			// "If value is the empty string, abort these steps and do nothing."
4019 			if (value === "") {
4020 				return;
4021 			}
4022 
4023 			value = normalizeFontSize(value);
4024 
4025 			// "If value is not one of the strings "xx-small", "x-small", "small",
4026 			// "medium", "large", "x-large", "xx-large", "xxx-large", and is not a
4027 			// valid CSS absolute length, then abort these steps and do nothing."
4028 			//
4029 			// More cheap hacks to skip valid CSS absolute length checks.
4030 			if (jQuery.inArray(value, ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) == -1 && !/^[0-9]+(\.[0-9]+)?(cm|mm|in|pt|pc)$/.test(value)) {
4031 				return;
4032 			}
4033 
4034 			// "Set the selection's value to value."
4035 			setSelectionValue("fontsize", value, range);
4036 		},
4037 		indeterm: function () {
4038 			// "True if among editable Text nodes that are effectively contained in
4039 			// the active range, there are two that have distinct effective command
4040 			// values.  Otherwise false."
4041 			return $_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) {
4042 				return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
4043 			})).map(function (node) {
4044 				return getEffectiveCommandValue(node, "fontsize");
4045 			}, true).filter(function (value, i, arr) {
4046 				return $_(arr.slice(0, i)).indexOf(value) == -1;
4047 			}).length >= 2;
4048 		},
4049 		value: function (range) {
4050 			// "Let pixel size be the effective command value of the first editable
4051 			// Text node that is effectively contained in the active range, or if
4052 			// there is no such node, the effective command value of the active
4053 			// range's start node, in either case interpreted as a number of
4054 			// pixels."
4055 			var node = getAllEffectivelyContainedNodes(range, function (node) {
4056 				return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
4057 			})[0];
4058 			if (node === undefined) {
4059 				node = range.startContainer;
4060 			}
4061 			var pixelSize = getEffectiveCommandValue(node, "fontsize");
4062 
4063 			// "Return the legacy font size for pixel size."
4064 			return getLegacyFontSize(pixelSize);
4065 		},
4066 		relevantCssProperty: "fontSize"
4067 	};
4068 
4069 	//@}
4070 	///// The foreColor command /////
4071 	//@{
4072 	commands.forecolor = {
4073 		action: function (value, range) {
4074 			// Copy-pasted, same as backColor and hiliteColor
4075 
4076 			// "If value is not a valid CSS color, prepend "#" to it."
4077 			//
4078 			// "If value is still not a valid CSS color, or if it is currentColor,
4079 			// abort these steps and do nothing."
4080 			//
4081 			// Cheap hack for testing, no attempt to be comprehensive.
4082 			if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) {
4083 				value = "#" + value;
4084 			}
4085 			if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") {
4086 				return;
4087 			}
4088 
4089 			// "Set the selection's value to value."
4090 			setSelectionValue("forecolor", value, range);
4091 		},
4092 		standardInlineValueCommand: true,
4093 		relevantCssProperty: "color",
4094 		equivalentValues: function (val1, val2) {
4095 			// "Either both strings are valid CSS colors and have the same red,
4096 			// green, blue, and alpha components, or neither string is a valid CSS
4097 			// color."
4098 			return normalizeColor(val1) === normalizeColor(val2);
4099 		}
4100 	};
4101 
4102 	//@}
4103 	///// The hiliteColor command /////
4104 	//@{
4105 	commands.hilitecolor = {
4106 		// Copy-pasted, same as backColor
4107 		action: function (value, range) {
4108 			// Action is further copy-pasted, same as foreColor
4109 
4110 			// "If value is not a valid CSS color, prepend "#" to it."
4111 			//
4112 			// "If value is still not a valid CSS color, or if it is currentColor,
4113 			// abort these steps and do nothing."
4114 			//
4115 			// Cheap hack for testing, no attempt to be comprehensive.
4116 			if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) {
4117 				value = "#" + value;
4118 			}
4119 			if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") {
4120 				return;
4121 			}
4122 
4123 			// "Set the selection's value to value."
4124 			setSelectionValue("hilitecolor", value, range);
4125 		},
4126 		indeterm: function () {
4127 			// "True if among editable Text nodes that are effectively contained in
4128 			// the active range, there are two that have distinct effective command
4129 			// values.  Otherwise false."
4130 			return $_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) {
4131 				return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
4132 			})).map(function (node) {
4133 				return getEffectiveCommandValue(node, "hilitecolor");
4134 			}, true).filter(function (value, i, arr) {
4135 				return $_(arr.slice(0, i)).indexOf(value) == -1;
4136 			}).length >= 2;
4137 		},
4138 		standardInlineValueCommand: true,
4139 		relevantCssProperty: "backgroundColor",
4140 		equivalentValues: function (val1, val2) {
4141 			// "Either both strings are valid CSS colors and have the same red,
4142 			// green, blue, and alpha components, or neither string is a valid CSS
4143 			// color."
4144 			return normalizeColor(val1) === normalizeColor(val2);
4145 		}
4146 	};
4147 
4148 	//@}
4149 	///// The italic command /////
4150 	//@{
4151 	commands.italic = {
4152 		action: function (value, range) {
4153 			// "If queryCommandState("italic") returns true, set the selection's
4154 			// value to "normal". Otherwise set the selection's value to "italic"."
4155 			if (myQueryCommandState("italic", range)) {
4156 				setSelectionValue("italic", "normal", range);
4157 			} else {
4158 				setSelectionValue("italic", "italic", range);
4159 			}
4160 		},
4161 		inlineCommandActivatedValues: ["italic", "oblique"],
4162 		relevantCssProperty: "fontStyle"
4163 	};
4164 
4165 	//@}
4166 	///// The removeFormat command /////
4167 	//@{
4168 	commands.removeformat = {
4169 		action: function (value, range) {
4170 			var newEnd, newStart, newNode;
4171 
4172 			// "A removeFormat candidate is an editable HTML element with local
4173 			// name "abbr", "acronym", "b", "bdi", "bdo", "big", "blink", "cite",
4174 			// "code", "dfn", "em", "font", "i", "ins", "kbd", "mark", "nobr", "q",
4175 			// "s", "samp", "small", "span", "strike", "strong", "sub", "sup",
4176 			// "tt", "u", or "var"."
4177 			function isRemoveFormatCandidate(node) {
4178 				return isEditable(node) && isHtmlElementInArray(node, ["abbr", "acronym", "b", "bdi", "bdo", "big", "blink", "cite", "code", "dfn", "em", "font", "i", "ins", "kbd", "mark", "nobr", "q", "s", "samp", "small", "span", "strike", "strong", "sub", "sup", "tt", "u", "var"]);
4179 			}
4180 
4181 			// "Let elements to remove be a list of every removeFormat candidate
4182 			// effectively contained in the active range."
4183 			var elementsToRemove = getAllEffectivelyContainedNodes(getActiveRange(), isRemoveFormatCandidate);
4184 
4185 			// "For each element in elements to remove:"
4186 			$_(elementsToRemove).forEach(function (element) {
4187 				// "While element has children, insert the first child of element
4188 				// into the parent of element immediately before element,
4189 				// preserving ranges."
4190 				while (element.hasChildNodes()) {
4191 					movePreservingRanges(element.firstChild, element.parentNode, Dom.getIndexInParent(element), getActiveRange());
4192 				}
4193 
4194 				// "Remove element from its parent."
4195 				element.parentNode.removeChild(element);
4196 			});
4197 
4198 			// "If the active range's start node is an editable Text node, and its
4199 			// start offset is neither zero nor its start node's length, call
4200 			// splitText() on the active range's start node, with argument equal to
4201 			// the active range's start offset. Then set the active range's start
4202 			// node to the result, and its start offset to zero."
4203 			if (isEditable(getActiveRange().startContainer) && getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset != 0 && getActiveRange().startOffset != getNodeLength(getActiveRange().startContainer)) {
4204 				// Account for browsers not following range mutation rules
4205 				if (getActiveRange().startContainer == getActiveRange().endContainer) {
4206 					newEnd = getActiveRange().endOffset - getActiveRange().startOffset;
4207 					newNode = splitText(getActiveRange().startContainer, getActiveRange().startOffset);
4208 					getActiveRange().setStart(newNode, 0);
4209 					getActiveRange().setEnd(newNode, newEnd);
4210 				} else {
4211 					getActiveRange().setStart(splitText(getActiveRange().startContainer, getActiveRange().startOffset), 0);
4212 				}
4213 			}
4214 
4215 			// "If the active range's end node is an editable Text node, and its
4216 			// end offset is neither zero nor its end node's length, call
4217 			// splitText() on the active range's end node, with argument equal to
4218 			// the active range's end offset."
4219 			if (isEditable(getActiveRange().endContainer) && getActiveRange().endContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().endOffset != 0 && getActiveRange().endOffset != getNodeLength(getActiveRange().endContainer)) {
4220 				// IE seems to mutate the range incorrectly here, so we need
4221 				// correction here as well.  Have to be careful to set the range to
4222 				// something not including the text node so that getActiveRange()
4223 				// doesn't throw an exception due to a temporarily detached
4224 				// endpoint.
4225 				newStart = [getActiveRange().startContainer, getActiveRange().startOffset];
4226 				newEnd = [getActiveRange().endContainer, getActiveRange().endOffset];
4227 				getActiveRange().setEnd(document.documentElement, 0);
4228 				splitText(newEnd[0], newEnd[1]);
4229 				getActiveRange().setStart(newStart[0], newStart[1]);
4230 				getActiveRange().setEnd(newEnd[0], newEnd[1]);
4231 			}
4232 
4233 			// "Let node list consist of all editable nodes effectively contained
4234 			// in the active range."
4235 			//
4236 			// "For each node in node list, while node's parent is a removeFormat
4237 			// candidate in the same editing host as node, split the parent of the
4238 			// one-node list consisting of node."
4239 			$_(getAllEffectivelyContainedNodes(getActiveRange(), isEditable)).forEach(function (node) {
4240 				while (isRemoveFormatCandidate(node.parentNode) && inSameEditingHost(node.parentNode, node)) {
4241 					splitParent([node], getActiveRange());
4242 				}
4243 			});
4244 
4245 			// "For each of the entries in the following list, in the given order,
4246 			// set the selection's value to null, with command as given."
4247 			$_(["subscript", "bold", "fontname", "fontsize", "forecolor", "hilitecolor", "italic", "strikethrough", "underline"]).forEach(function (command) {
4248 				setSelectionValue(command, null, range);
4249 			});
4250 		}
4251 	};
4252 
4253 	//@}
4254 	///// The strikethrough command /////
4255 	//@{
4256 	commands.strikethrough = {
4257 		action: function (value, range) {
4258 			// "If queryCommandState("strikethrough") returns true, set the
4259 4260 			// selection's value to null. Otherwise set the selection's value to
4261 			// "line-through"."
4262 			if (myQueryCommandState("strikethrough", range)) {
4263 				setSelectionValue("strikethrough", null, range);
4264 			} else {
4265 4266 				setSelectionValue("strikethrough", "line-through", range);
4267 			}
4268 		},
4269 		inlineCommandActivatedValues: ["line-through"]
4270 	};
4271 
4272 	//@}
4273 	///// The subscript command /////
4274 	//@{
4275 	commands.subscript = {
4276 		action: function (value, range) {
4277 			// "Call queryCommandState("subscript"), and let state be the result."
4278 			var state = myQueryCommandState("subscript", range);
4279 
4280 			// "Set the selection's value to null."
4281 			setSelectionValue("subscript", null, range);
4282 
4283 			// "If state is false, set the selection's value to "subscript"."
4284 			if (!state) {
4285 				setSelectionValue("subscript", "subscript", range);
4286 			}
4287 		},
4288 		indeterm: function () {
4289 			// "True if either among editable Text nodes that are effectively
4290 			// contained in the active range, there is at least one with effective
4291 			// command value "subscript" and at least one with some other effective
4292 			// command value; or if there is some editable Text node effectively
4293 			// contained in the active range with effective command value "mixed".
4294 			// Otherwise false."
4295 			var nodes = getAllEffectivelyContainedNodes(getActiveRange(), function (node) {
4296 				return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
4297 			});
4298 			return (($_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") == "subscript"; })
4299 					 && $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") != "subscript"; }))
4300 					|| $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") == "mixed"; }));
4301 		},
4302 		inlineCommandActivatedValues: ["subscript"]
4303 	};
4304 
4305 	//@}
4306 	///// The superscript command /////
4307 	//@{
4308 	commands.superscript = {
4309 		action: function (value, range) {
4310 			// "Call queryCommandState("superscript"), and let state be the
4311 			// result."
4312 			var state = myQueryCommandState("superscript", range);
4313 
4314 			// "Set the selection's value to null."
4315 			setSelectionValue("superscript", null, range);
4316 
4317 			// "If state is false, set the selection's value to "superscript"."
4318 			if (!state) {
4319 				setSelectionValue("superscript", "superscript", range);
4320 			}
4321 		},
4322 		indeterm: function () {
4323 			// "True if either among editable Text nodes that are effectively
4324 			// contained in the active range, there is at least one with effective
4325 			// command value "superscript" and at least one with some other
4326 			// effective command value; or if there is some editable Text node
4327 			// effectively contained in the active range with effective command
4328 			// value "mixed".  Otherwise false."
4329 			var nodes = getAllEffectivelyContainedNodes(
4330 				getActiveRange(),
4331 				function (node) {
4332 					return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
4333 				}
4334 			);
4335 			return (($_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") == "superscript"; })
4336 					 && $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") != "superscript"; }))
4337 					|| $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") == "mixed"; }));
4338 		},
4339 		inlineCommandActivatedValues: ["superscript"]
4340 	};
4341 
4342 	//@}
4343 	///// The underline command /////
4344 	//@{
4345 	commands.underline = {
4346 		action: function (value, range) {
4347 			// "If queryCommandState("underline") returns true, set the selection's
4348 			// value to null. Otherwise set the selection's value to "underline"."
4349 			if (myQueryCommandState("underline", range)) {
4350 				setSelectionValue("underline", null, range);
4351 			} else {
4352 				setSelectionValue("underline", "underline", range);
4353 			}
4354 		},
4355 		inlineCommandActivatedValues: ["underline"]
4356 	};
4357 
4358 	//@}
4359 	///// The unlink command /////
4360 	//@{
4361 	commands.unlink = {
4362 		action: function () {
4363 			// "Let hyperlinks be a list of every a element that has an href
4364 			// attribute and is contained in the active range or is an ancestor of
4365 			// one of its boundary points."
4366 			//
4367 			// As usual, take care to ensure it's tree order.  The correctness of
4368 			// the following is left as an exercise for the reader.
4369 			var range = getActiveRange();
4370 			var hyperlinks = [];
4371 			var node;
4372 			for (node = range.startContainer; node; node = node.parentNode) {
4373 				if (isNamedHtmlElement(node, 'A') && hasAttribute(node, "href")) {
4374 					hyperlinks.unshift(node);
4375 				}
4376 			}
4377 			for (node = range.startContainer; node != nextNodeDescendants(range.endContainer); node = nextNode(node)) {
4378 				if (isNamedHtmlElement(node, 'A') && hasAttribute(node, "href") && (isContained(node, range) || isAncestor(node, range.endContainer) || node == range.endContainer)) {
4379 					hyperlinks.push(node);
4380 				}
4381 			}
4382 
4383 			// "Clear the value of each member of hyperlinks."
4384 			var i;
4385 			for (i = 0; i < hyperlinks.length; i++) {
4386 				clearValue(hyperlinks[i], "unlink", range);
4387 			}
4388 		},
4389 		standardInlineValueCommand: true
4390 	};
4391 
4392 	//@}
4393 
4394 	/////////////////////////////////////
4395 	///// Block formatting commands /////
4396 	/////////////////////////////////////
4397 
4398 	///// Block formatting command definitions /////
4399 	//@{
4400 
4401 	// "An indentation element is either a blockquote, or a div that has a style
4402 	// attribute that sets "margin" or some subproperty of it."
4403 	function isIndentationElement(node) {
4404 		// Handling of indentation elements while deleting is somehow broken (pressing backspace
4405 		// in blockquotes wraps the blockquote into a div, ...)
4406 		// therefore for now, we pretend that indentation elements do not exist at all.
4407 		return false;
4408 	}
4409 
4410 	// "A simple indentation element is an indentation element that has no
4411 	// attributes other than one or more of
4412 	//
4413 	//   * "a style attribute that sets no properties other than "margin", "border",
4414 	//     "padding", or subproperties of those;
4415 	//   * "a class attribute;
4416 	//   * "a dir attribute."
4417 	function isSimpleIndentationElement(node) {
4418 		if (!isIndentationElement(node)) {
4419 			return false;
4420 		}
4421 
4422 		if (node.tagName != "BLOCKQUOTE" && node.tagName != "DIV") {
4423 			return false;
4424 		}
4425 
4426 		var i;
4427 		for (i = 0; i < node.attributes.length; i++) {
4428 			if (!isHtmlNamespace(node.attributes[i].namespaceURI) || jQuery.inArray(node.attributes[i].name, ["style", "class", "dir"]) == -1) {
4429 				return false;
4430 			}
4431 		}
4432 
4433 		if (typeof node.style.length !== 'undefined') {
4434 			for (i = 0; i < node.style.length; i++) {
4435 				// This is approximate, but it works well enough for my purposes.
4436 				if (!/^(-[a-z]+-)?(margin|border|padding)/.test(node.style[i])) {
4437 					return false;
4438 				}
4439 			}
4440 		} else {
4441 			var s;
4442 			/*jslint forin: true*/ //not sure whether node.style.hasOwnProperty is valid
4443 			for (s in node.style) {
4444 				// This is approximate, but it works well enough for my purposes.
4445 				if (!/^(-[a-z]+-)?(margin|border|padding)/.test(s) && node.style[s] && node.style[s] !== 0 && node.style[s] !== 'false') {
4446 					return false;
4447 				}
4448 			}
4449 			/*jslint forin: false*/
4450 		}
4451 
4452 		return true;
4453 	}
4454 
4455 	// "A non-list single-line container is an HTML element with local name
4456 	// "address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre",
4457 	// or "xmp"."
4458 	function isNonListSingleLineContainer(node) {
4459 		return isHtmlElementInArray(node, ["address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", "xmp"]);
4460 	}
4461 
4462 	// "A single-line container is either a non-list single-line container, or an
4463 	// HTML element with local name "li", "dt", or "dd"."
4464 	function isSingleLineContainer(node) {
4465 		return isNonListSingleLineContainer(node) || isHtmlElementInArray(node, ["li", "dt", "dd"]);
4466 	}
4467 
4468 	// "The default single-line container name is "p"."
4469 	var defaultSingleLineContainerName = "p";
4470 
4471 	//@}
4472 	///// Check whether the given element is an end break /////
4473 	//@{
4474 	function isEndBreak(element) {
4475 		return (isNamedHtmlElement(element, 'br') && element.parentNode.lastChild === element);
4476 	}
4477 
4478 	//@}
4479 	///// Create an end break /////
4480 	//@{
4481 	function createEndBreak() {
4482 		return document.createElement("br");
4483 	}
4484 
4485 	/**
4486 	 * Ensure the container is editable
4487 	 * E.g. when called for an empty paragraph or header, and the browser is not IE,
4488 	 * we need to append a br (marked with class aloha-end-br)
4489 	 * For IE7, there is a special behaviour that will append zero-width whitespace
4490 	 * @param {DOMNode} container
4491 	 */
4492 	function ensureContainerEditable(container) {
4493 		if (!container) {
4494 			return;
4495 		}
4496 
4497 		// Because it is useful to be able to completely empty the contents of
4498 		// an editing host during editing.  So long as the container's
4499 		// contenteditable attribute is "true" (as is the case during editing),
4500 		// the element will be rendered visibly in all browsers.  This fact
4501 		// allows us to not have to prop up the container with a <br> in order
4502 		// to keep it accessible to the editor.
4503 		if (isEditingHost(container)) {
4504 			return;
4505 		}
4506 
4507 		if (isNamedHtmlElement(container.lastChild, "br")) {
4508 			return;
4509 		}
4510 
4511 		if ($_(container.childNodes).some(isVisible)) {
4512 			return;
4513 		}
4514 
4515 		if (!jQuery.browser.msie) {
4516 			// for normal browsers, the end-br will do
4517 			container.appendChild(createEndBreak());
4518 		} else if (jQuery.browser.msie && jQuery.browser.version <= 7 && isHtmlElementInArray(container, ["p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote"])) {
4519 			// for IE7, we need to insert a text node containing a single zero-width whitespace character
4520 			if (!container.firstChild) {
4521 				container.appendChild(document.createTextNode('\u200b'));
4522 			}
4523 		}
4524 	}
4525 
4526 	//@}
4527 	///// Assorted block formatting command algorithms /////
4528 	//@{
4529 
4530 	function fixDisallowedAncestors(node, range) {
4531 		var i;
4532 
4533 		// "If node is not editable, abort these steps."
4534 		if (!isEditable(node)) {
4535 			return;
4536 		}
4537 
4538 		// "If node is not an allowed child of any of its ancestors in the same
4539 		// editing host, and is not an HTML element with local name equal to the
4540 		// default single-line container name:"
4541 		if ($_(getAncestors(node)).every(function (ancestor) { return !inSameEditingHost(node, ancestor) || !isAllowedChild(node, ancestor); })
4542 			    && !isHtmlElement_obsolete(node, defaultSingleLineContainerName)) {
4543 			// "If node is a dd or dt, wrap the one-node list consisting of node,
4544 			// with sibling criteria returning true for any dl with no attributes
4545 			// and false otherwise, and new parent instructions returning the
4546 			// result of calling createElement("dl") on the context object. Then
4547 			// abort these steps."
4548 			if (isHtmlElementInArray(node, ["dd", "dt"])) {
4549 				wrap(
4550 					[node],
4551 					function (sibling) {
4552 						return isNamedHtmlElement(sibling, 'dl') && !sibling.attributes.length;
4553 					},
4554 					function () {
4555 						return document.createElement("dl");
4556 					},
4557 					range
4558 				);
4559 				return;
4560 			}
4561 
4562 			// "If node is not a prohibited paragraph child, abort these steps."
4563 			if (!isProhibitedParagraphChild(node)) {
4564 				return;
4565 			}
4566 
4567 			// "Set the tag name of node to the default single-line container name,
4568 			// and let node be the result."
4569 			node = setTagName(node, defaultSingleLineContainerName, range);
4570 
4571 			ensureContainerEditable(node);
4572 
4573 			// "Fix disallowed ancestors of node."
4574 			fixDisallowedAncestors(node, range);
4575 
4576 			// "Let descendants be all descendants of node."
4577 			var descendants = getDescendants(node);
4578 
4579 			// "Fix disallowed ancestors of each member of descendants."
4580 			for (i = 0; i < descendants.length; i++) {
4581 				fixDisallowedAncestors(descendants[i], range);
4582 			}
4583 
4584 			// "Abort these steps."
4585 			return;
4586 		}
4587 
4588 		// "Record the values of the one-node list consisting of node, and let
4589 		// values be the result."
4590 		var values = recordValues([node]);
4591 		var newStartOffset, newEndOffset;
4592 
4593 		// "While node is not an allowed child of its parent, split the parent of
4594 		// the one-node list consisting of node."
4595 		while (!isAllowedChild(node, node.parentNode)) {
4596 			// If the parent contains only this node and possibly empty text nodes, we rather want to unwrap the node, instead of splitting.
4597 			// With splitting, we would get empty nodes, like:
4598 			// split: <p><p>foo</p></p> -> <p></p><p>foo</p> (bad)
4599 			// unwrap: <p><p>foo</p></p> -> <p>foo</p> (good)
4600 
4601 			// First remove empty text nodes that are children of the parent and correct the range if necessary
4602 			// we do this to have the node being the only child of its parent, so that we can replace the parent with the node
4603 			for (i = node.parentNode.childNodes.length - 1; i >= 0; --i) {
4604 				if (node.parentNode.childNodes[i].nodeType == 3 && node.parentNode.childNodes[i].data.length == 0) {
4605 					// we remove the empty text node
4606 					node.parentNode.removeChild(node.parentNode.childNodes[i]);
4607 
4608 					// if the range points to somewhere behind the removed text node, we reduce the offset
4609 					if (range.startContainer == node.parentNode && range.startOffset > i) {
4610 						range.startOffset--;
4611 					}
4612 					if (range.endContainer == node.parentNode && range.endOffset > i) {
4613 						range.endOffset--;
4614 					}
4615 				}
4616 			}
4617 
4618 			// now that the parent has only the node as child (because we
4619 			// removed any existing empty text nodes), we can safely unwrap the
4620 			// node's contents, and correct the range if necessary
4621 			if (node.parentNode.childNodes.length == 1) {
4622 				newStartOffset = range.startOffset;
4623 				newEndOffset = range.endOffset;
4624 
4625 				if (range.startContainer === node.parentNode && range.startOffset > Dom.getIndexInParent(node)) {
4626 					// the node (1 element) will be replaced by its contents (contents().length elements)
4627 					newStartOffset = range.startOffset + (jQuery(node).contents().length - 1);
4628 				}
4629 				if (range.endContainer === node.parentNode && range.endOffset > Dom.getIndexInParent(node)) {
4630 					// the node (1 element) will be replaced by its contents (contents().length elements)
4631 					newEndOffset = range.endOffset + (jQuery(node).contents().length - 1);
4632 				}
4633 				jQuery(node).contents().unwrap();
4634 				range.startOffset = newStartOffset;
4635 				range.endOffset = newEndOffset;
4636 4637 				// after unwrapping, we are done
4638 				break;
4639 			} else {
4640 				// store the original parent
4641 				var originalParent = node.parentNode;
4642 				splitParent([node], range);
4643 				// check whether the parent did not change, so the split did not work, e.g.
4644 				// because we already reached the editing host itself.
4645 				// this situation can occur, e.g. when we insert a paragraph into an contenteditable span
4646 				// in such cases, we just unwrap the contents of the paragraph
4647 				if (originalParent === node.parentNode) {
4648 					// so we unwrap now
4649 					newStartOffset = range.startOffset;
4650 					newEndOffset = range.endOffset;
4651 
4652 					if (range.startContainer === node.parentNode && range.startOffset > Dom.getIndexInParent(node)) {
4653 						// the node (1 element) will be replaced by its contents (contents().length elements)
4654 						newStartOffset = range.startOffset + (jQuery(node).contents().length - 1);
4655 					}
4656 					if (range.endContainer === node.parentNode && range.endOffset > Dom.getIndexInParent(node)) {
4657 						// the node (1 element) will be replaced by its contents (contents().length elements)
4658 						newEndOffset = range.endOffset + (jQuery(node).contents().length - 1);
4659 					}
4660 					jQuery(node).contents().unwrap();
4661 					range.startOffset = newStartOffset;
4662 					range.endOffset = newEndOffset;
4663 					// after unwrapping, we are done
4664 					break;
4665 				}
4666 			}
4667 		}
4668 
4669 		// "Restore the values from values."
4670 		restoreValues(values, range);
4671 	}
4672 4673 
	/**
4674 	 * This method "normalizes" sublists of the given item (which is supposed to be a LI):
4675 	 * If sublists are found in the LI element, they are moved directly into the outer list.
4676 	 * @param item item
4677 	 * @param range range, which will be modified if necessary
4678 	 */
4679 	function normalizeSublists(item, range) {
4680 		// "If item is not an li or it is not editable or its parent is not
4681 		// editable, abort these steps."
4682 		if (!isNamedHtmlElement(item, 'LI') || !isEditable(item) || !isEditable(item.parentNode)) {
4683 			return;
4684 		}
4685 
4686 		// "Let new item be null."
4687 		var newItem = null;
4688 
4689 		function isOlUl(node) {
4690 			return isHtmlElementInArray(node, ["OL", "UL"]);
4691 		}
4692 
4693 		// "While item has an ol or ul child:"
4694 		while ($_(item.childNodes).some(isOlUl)) {
4695 			// "Let child be the last child of item."
4696 4697 			var child = item.lastChild;
4698 
4699 			// "If child is an ol or ul, or new item is null and child is a Text
4700 			// node whose data consists of zero of more space characters:"
4701 			if (isHtmlElementInArray(child, ["OL", "UL"]) || (!newItem && child.nodeType == $_.Node.TEXT_NODE && /^[ \t\n\f\r]*$/.test(child.data))) {
4702 				// "Set new item to null."
4703 				newItem = null;
4704 
4705 				// "Insert child into the parent of item immediately following
4706 				// item, preserving ranges."
4707 				movePreservingRanges(child, item.parentNode, 1 + Dom.getIndexInParent(item), range);
4708 
4709 				// "Otherwise:"
4710 			} else {
4711 				// "If new item is null, let new item be the result of calling
4712 				// createElement("li") on the ownerDocument of item, then insert
4713 				// new item into the parent of item immediately after item."
4714 				if (!newItem) {
4715 					newItem = item.ownerDocument.createElement("li");
4716 					item.parentNode.insertBefore(newItem, item.nextSibling);
4717 				}
4718 
4719 				// "Insert child into new item as its first child, preserving
4720 				// ranges."
4721 				movePreservingRanges(child, newItem, 0, range);
4722 			}
4723 		}
4724 	}
4725 
4726 	/**
4727 	 * This method is the exact opposite of normalizeSublists.
4728 	 * List nodes directly nested into each other are corrected to be nested in li elements (so that the resulting lists conform the html5 specification)
4729 	 * @param item list node
4730 	 * @param range range, which is preserved when modifying the list
4731 	 */
4732 	function unNormalizeSublists(item, range) {
4733 		// "If item is not an ol or ol or it is not editable or its parent is not
4734 		// editable, abort these steps."
4735 		if (!isHtmlElementInArray(item, ["OL", "UL"]) || !isEditable(item)) {
4736 			return;
4737 		}
4738 
4739 		var $list = jQuery(item);
4740 		$list.children("ol,ul").each(function (index, sublist) {
4741 			if (isNamedHtmlElement(sublist.previousSibling, "LI")) {
4742 				// move the sublist into the LI
4743 				movePreservingRanges(sublist, sublist.previousSibling, sublist.previousSibling.childNodes.length, range);
4744 			}
4745 		});
4746 	}
4747 
4748 	//@}
4749 	///// Block-extending a range /////
4750 	//@{
4751 
4752 	function blockExtend(range) {
4753 		// "Let start node, start offset, end node, and end offset be the start
4754 		// and end nodes and offsets of the range."
4755 		var startNode = range.startContainer;
4756 		var startOffset = range.startOffset;
4757 		var endNode = range.endContainer;
4758 		var endOffset = range.endOffset;
4759 
4760 		// "If some ancestor container of start node is an li, set start offset to
4761 		// the index of the last such li in tree order, and set start node to that
4762 		// li's parent."
4763 		var liAncestors = $_(getAncestors(startNode).concat(startNode)).filter(function (ancestor) { return isNamedHtmlElement(ancestor, 'li'); }).slice(-1);
4764 		if (liAncestors.length) {
4765 			startOffset = Dom.getIndexInParent(liAncestors[0]);
4766 			startNode = liAncestors[0].parentNode;
4767 		}
4768 
4769 		// "If (start node, start offset) is not a block start point, repeat the
4770 		// following steps:"
4771 		if (!isBlockStartPoint(startNode, startOffset)) {
4772 			do {
4773 				// "If start offset is zero, set it to start node's index, then set
4774 				// start node to its parent."
4775 				if (startOffset == 0) {
4776 					startOffset = Dom.getIndexInParent(startNode);
4777 					startNode = startNode.parentNode;
4778 
4779 					// "Otherwise, subtract one from start offset."
4780 				} else {
4781 					startOffset--;
4782 				}
4783 
4784 				// "If (start node, start offset) is a block boundary point, break from
4785 				// this loop."
4786 			} while (!isBlockBoundaryPoint(startNode, startOffset));
4787 		}
4788 
4789 		// "While start offset is zero and start node's parent is not null, set
4790 		// start offset to start node's index, then set start node to its parent."
4791 		while (startOffset == 0 && startNode.parentNode) {
4792 			startOffset = Dom.getIndexInParent(startNode);
4793 			startNode = startNode.parentNode;
4794 		}
4795 
4796 		// "If some ancestor container of end node is an li, set end offset to one
4797 		// plus the index of the last such li in tree order, and set end node to
4798 		// that li's parent."
4799 		liAncestors = $_(getAncestors(endNode).concat(endNode)).filter(function (ancestor) { return isNamedHtmlElement(ancestor, 'li'); }).slice(-1);
4800 		if (liAncestors.length) {
4801 			endOffset = 1 + Dom.getIndexInParent(liAncestors[0]);
4802 			endNode = liAncestors[0].parentNode;
4803 		}
4804 
4805 		// "If (end node, end offset) is not a block end point, repeat the
4806 		// following steps:"
4807 		if (!isBlockEndPoint(endNode, endOffset)) {
4808 			do {
4809 				// "If end offset is end node's length, set it to one plus end node's
4810 				// index, then set end node to its parent."
4811 				if (endOffset == getNodeLength(endNode)) {
4812 					endOffset = 1 + Dom.getIndexInParent(endNode);
4813 					endNode = endNode.parentNode;
4814 
4815 					// "Otherwise, add one to end offset.
4816 				} else {
4817 					endOffset++;
4818 				}
4819 
4820 				// "If (end node, end offset) is a block boundary point, break from
4821 				// this loop."
4822 			} while (!isBlockBoundaryPoint(endNode, endOffset));
4823 		}
4824 
4825 		// "While end offset is end node's length and end node's parent is not
4826 		// null, set end offset to one plus end node's index, then set end node to
4827 		// its parent."
4828 		while (endOffset == getNodeLength(endNode) && endNode.parentNode) {
4829 			endOffset = 1 + Dom.getIndexInParent(endNode);
4830 			endNode = endNode.parentNode;
4831 		}
4832 
4833 		// "Let new range be a new range whose start and end nodes and offsets
4834 		// are start node, start offset, end node, and end offset."
4835 		var newRange = Aloha.createRange();
4836 		newRange.setStart(startNode, startOffset);
4837 		newRange.setEnd(endNode, endOffset);
4838 
4839 		// "Return new range."
4840 		return newRange;
4841 	}
4842 
4843 	function getSelectionListState() {
4844 		// "Block-extend the active range, and let new range be the result."
4845 		var newRange = blockExtend(getActiveRange());
4846 
4847 		// "Let node list be a list of nodes, initially empty."
4848 		//
4849 		// "For each node contained in new range, append node to node list if the
4850 		// last member of node list (if any) is not an ancestor of node; node is
4851 		// editable; node is not an indentation element; and node is either an ol
4852 		// or ul, or the child of an ol or ul, or an allowed child of "li"."
4853 		var nodeList = getContainedNodes(newRange, function (node) {
4854 			return isEditable(node) && !isIndentationElement(node) && (isHtmlElementInArray(node, ["ol", "ul"]) || isHtmlElementInArray(node.parentNode, ["ol", "ul"]) || isAllowedChild(node, "li"));
4855 		});
4856 
4857 		// "If node list is empty, return "none"."
4858 		if (!nodeList.length) {
4859 			return "none";
4860 		}
4861 
4862 		// "If every member of node list is either an ol or the child of an ol or
4863 		// the child of an li child of an ol, and none is a ul or an ancestor of a
4864 		// ul, return "ol"."
4865 		if ($_(nodeList).every(function (node) { return (isNamedHtmlElement(node, 'ol')
4866 														 || isNamedHtmlElement(node.parentNode, "ol")
4867 														 || (isNamedHtmlElement(node.parentNode, "li")
4868 															 && isNamedHtmlElement(node.parentNode.parentNode, "ol"))); })
4869 			    && !$_(nodeList).some(function (node) { return isNamedHtmlElement(node, 'ul') || (node.querySelector && node.querySelector("ul")); })) {
4870 			return "ol";
4871 		}
4872 
4873 		// "If every member of node list is either a ul or the child of a ul or the
4874 		// child of an li child of a ul, and none is an ol or an ancestor of an ol,
4875 		// return "ul"."
4876 		if ($_(nodeList).every(function (node) { return (isNamedHtmlElement(node, 'ul')
4877 														 || isNamedHtmlElement(node.parentNode, "ul")
4878 														 || (isNamedHtmlElement(node.parentNode, "li")
4879 															 && isNamedHtmlElement(node.parentNode.parentNode, "ul"))); })
4880 			    && !$_(nodeList).some(function (node) { return isNamedHtmlElement(node, 'ol') || (node.querySelector && node.querySelector("ol")); })) {
4881 			return "ul";
4882 		}
4883 
4884 		var hasOl = $_(nodeList).some(function (node) {
4885 			return (isNamedHtmlElement(node, 'ol')
4886 					|| isNamedHtmlElement(node.parentNode, "ol")
4887 					|| (node.querySelector && node.querySelector("ol"))
4888 					|| (isNamedHtmlElement(node.parentNode, "li")
4889 						&& isNamedHtmlElement(node.parentNode.parentNode, "ol")));
4890 		});
4891 		var hasUl = $_(nodeList).some(function (node) {
4892 			return (isNamedHtmlElement(node, 'ul')
4893 					|| isNamedHtmlElement(node.parentNode, "ul")
4894 					|| (node.querySelector && node.querySelector("ul"))
4895 					|| (isNamedHtmlElement(node.parentNode, "li")
4896 						&& isNamedHtmlElement(node.parentNode.parentNode, "ul")));
4897 		});
4898 		// "If some member of node list is either an ol or the child or ancestor of
4899 		// an ol or the child of an li child of an ol, and some member of node list
4900 		// is either a ul or the child or ancestor of a ul or the child of an li
4901 		// child of a ul, return "mixed"."
4902 		if (hasOl && hasUl) {
4903 			return "mixed";
4904 		}
4905 
4906 		// "If some member of node list is either an ol or the child or ancestor of
4907 		// an ol or the child of an li child of an ol, return "mixed ol"."
4908 		if (hasOl) {
4909 			return "mixed ol";
4910 		}
4911 
4912 		// "If some member of node list is either a ul or the child or ancestor of
4913 		// a ul or the child of an li child of a ul, return "mixed ul"."
4914 		if (hasUl) {
4915 			return "mixed ul";
4916 		}
4917 
4918 		// "Return "none"."
4919 		return "none";
4920 	}
4921 
4922 	function getAlignmentValue(node) {
4923 		// "While node is neither null nor an Element, or it is an Element but its
4924 		// "display" property has resolved value "inline" or "none", set node to
4925 		// its parent."
4926 		while ((node && node.nodeType != $_.Node.ELEMENT_NODE) || (node.nodeType == $_.Node.ELEMENT_NODE && jQuery.inArray($_.getComputedStyle(node).display, ["inline", "none"]) != -1)) {
4927 			node = node.parentNode;
4928 		}
4929 
4930 		// "If node is not an Element, return "left"."
4931 		if (!node || node.nodeType != $_.Node.ELEMENT_NODE) {
4932 			return "left";
4933 		}
4934 
4935 		var resolvedValue = $_.getComputedStyle(node).textAlign
4936 		// Hack around browser non-standardness
4937 			.replace(/^-(moz|webkit)-/, "").replace(/^auto$/, "start");
4938 
4939 		// "If node's "text-align" property has resolved value "start", return
4940 		// "left" if the directionality of node is "ltr", "right" if it is "rtl"."
4941 		if (resolvedValue == "start") {
4942 			return getDirectionality(node) == "ltr" ? "left" : "right";
4943 		}
4944 
4945 		// "If node's "text-align" property has resolved value "end", return
4946 		// "right" if the directionality of node is "ltr", "left" if it is "rtl"."
4947 		if (resolvedValue == "end") {
4948 			return getDirectionality(node) == "ltr" ? "right" : "left";
4949 		}
4950 
4951 		// "If node's "text-align" property has resolved value "center", "justify",
4952 		// "left", or "right", return that value."
4953 		if (jQuery.inArray(resolvedValue, ["center", "justify", "left", "right"]) != -1) {
4954 			return resolvedValue;
4955 		}
4956 
4957 		// "Return "left"."
4958 		return "left";
4959 	}
4960 
4961 	//@}
4962 	///// Recording and restoring overrides /////
4963 	//@{
4964 
4965 	function recordCurrentOverrides(range) {
4966 		// "Let overrides be a list of (string, string or boolean) ordered pairs,
4967 		// initially empty."
4968 		var overrides = [];
4969 
4970 		// "If there is a value override for "createLink", add ("createLink", value
4971 		// override for "createLink") to overrides."
4972 		if (getValueOverride("createlink", range) !== undefined) {
4973 			overrides.push(["createlink", getValueOverride("createlink", range)]);
4974 		}
4975 
4976 		// "For each command in the list "bold", "italic", "strikethrough",
4977 		// "subscript", "superscript", "underline", in order: if there is a state
4978 		// override for command, add (command, command's state override) to
4979 		// overrides."
4980 		$_(["bold", "italic", "strikethrough", "subscript", "superscript", "underline"]).forEach(function (command) {
4981 			if (getStateOverride(command, range) !== undefined) {
4982 				overrides.push([command, getStateOverride(command, range)]);
4983 			}
4984 		});
4985 
4986 		// "For each command in the list "fontName", "fontSize", "foreColor",
4987 		// "hiliteColor", in order: if there is a value override for command, add
4988 		// (command, command's value override) to overrides."
4989 		$_(["fontname", "fontsize", "forecolor", "hilitecolor"]).forEach(function (command) {
4990 			if (getValueOverride(command, range) !== undefined) {
4991 				overrides.push([command, getValueOverride(command, range)]);
4992 			}
4993 		});
4994 
4995 		// "Return overrides."
4996 		return overrides;
4997 	}
4998 
4999 	function recordCurrentStatesAndValues(range) {
5000 		// "Let overrides be a list of (string, string or boolean) ordered pairs,
5001 		// initially empty."
5002 		var overrides = [];
5003 
5004 		// "Let node be the first editable Text node effectively contained in the
5005 		// active range, or null if there is none."
5006 		var node = $_(getAllEffectivelyContainedNodes(range)).filter(function (node) {
5007 			return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
5008 		})[0];
5009 
5010 		// "If node is null, return overrides."
5011 		if (!node) {
5012 			return overrides;
5013 		}
5014 
5015 		// "Add ("createLink", value for "createLink") to overrides."
5016 		overrides.push(["createlink", commands.createlink.value(range)]);
5017 
5018 		// "For each command in the list "bold", "italic", "strikethrough",
5019 		// "subscript", "superscript", "underline", in order: if node's effective
5020 		// command value for command is one of its inline command activated values,
5021 		// add (command, true) to overrides, and otherwise add (command, false) to
5022 		// overrides."
5023 		$_(["bold", "italic", "strikethrough", "subscript", "superscript", "underline"]).forEach(function (command) {
5024 			if ($_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(node, command)) != -1) {
5025 				overrides.push([command, true]);
5026 			} else {
5027 				overrides.push([command, false]);
5028 			}
5029 		});
5030 
5031 		// "For each command in the list "fontName", "foreColor", "hiliteColor", in
5032 		// order: add (command, command's value) to overrides."
5033 
5034 		$_(["fontname", "fontsize", "forecolor", "hilitecolor"]).forEach(function (command) {
5035 			overrides.push([command, commands[command].value(range)]);
5036 		});
5037 
5038 		// "Add ("fontSize", node's effective command value for "fontSize") to
5039 		// overrides."
5040 		overrides.push(["fontsize", getEffectiveCommandValue(node, "fontsize")]);
5041 
5042 		// "Return overrides."
5043 		return overrides;
5044 	}
5045 
5046 	function restoreStatesAndValues(overrides, range) {
5047 		var i;
5048 		var command;
5049 		var override;
5050 		// "Let node be the first editable Text node effectively contained in the
5051 		// active range, or null if there is none."
5052 		var node = $_(getAllEffectivelyContainedNodes(range)).filter(function (node) {
5053 			return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
5054 		})[0];
5055 
5056 		function isEditableTextNode(node) {
5057 			return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
5058 		}
5059 
5060 		// "If node is not null, then for each (command, override) pair in
5061 		// overrides, in order:"
5062 		if (node) {
5063 
5064 			for (i = 0; i < overrides.length; i++) {
5065 				command = overrides[i][0];
5066 				override = overrides[i][1];
5067 
5068 				// "If override is a boolean, and queryCommandState(command)
5069 				// returns something different from override, call
5070 				// execCommand(command)."
5071 				if (typeof override == "boolean" && myQueryCommandState(command, range) != override) {
5072 					myExecCommand(command, false, override, range);
5073 
5074 					// "Otherwise, if override is a string, and command is not
5075 					// "fontSize", and queryCommandValue(command) returns something not
5076 					// equivalent to override, call execCommand(command, false,
5077 					// override)."
5078 				} else if (typeof override == "string" && command != "fontsize" && !areEquivalentValues(command, myQueryCommandValue(command, range), override)) {
5079 					myExecCommand(command, false, override, range);
5080 
5081 					// "Otherwise, if override is a string; and command is "fontSize";
5082 					// and either there is a value override for "fontSize" that is not
5083 					// equal to override, or there is no value override for "fontSize"
5084 					// and node's effective command value for "fontSize" is not loosely
5085 					// equivalent to override: call execCommand("fontSize", false,
5086 					// override)."
5087 				} else if (typeof override == "string"
5088 						   && command == "fontsize"
5089 						   && ((getValueOverride("fontsize", range) !== undefined
5090 								&& getValueOverride("fontsize", range) !== override)
5091 							   || (getValueOverride("fontsize", range) === undefined
5092 								   && !areLooselyEquivalentValues(command, getEffectiveCommandValue(node, "fontsize"), override)))) {
5093 					myExecCommand("fontsize", false, override, range);
5094 
5095 					// "Otherwise, continue this loop from the beginning."
5096 				} else {
5097 					continue;
5098 				}
5099 
5100 				// "Set node to the first editable Text node effectively contained
5101 				// in the active range, if there is one."
5102 				node = $_(getAllEffectivelyContainedNodes(range)).filter(isEditableTextNode)[0] || node;
5103 5104 			}
5105 
5106 			// "Otherwise, for each (command, override) pair in overrides, in order:"
5107 		} else {
5108 			for (i = 0; i < overrides.length; i++) {
5109 				command = overrides[i][0];
5110 				override = overrides[i][1];
5111 
5112 				// "If override is a boolean, set the state override for command to
5113 				// override."
5114 				if (typeof override == "boolean") {
5115 					setStateOverride(command, override, range);
5116 				}
5117 
5118 				// "If override is a string, set the value override for command to
5119 				// override."
5120 				if (typeof override == "string") {
5121 					setValueOverride(command, override, range);
5122 				}
5123 			}
5124 		}
5125 	}
5126 
5127 	//@}
5128 	///// Canonical space sequences /////
5129 	//@{
5130 
5131 	function canonicalSpaceSequence(n, nonBreakingStart, nonBreakingEnd) {
5132 		// "If n is zero, return the empty string."
5133 		if (n == 0) {
5134 			return "";
5135 		}
5136 
5137 		// "If n is one and both non-breaking start and non-breaking end are false,
5138 		// return a single space (U+0020)."
5139 		if (n == 1 && !nonBreakingStart && !nonBreakingEnd) {
5140 			return " ";
5141 		}
5142 
5143 		// "If n is one, return a single non-breaking space (U+00A0)."
5144 		if (n == 1) {
5145 			return "\xa0";
5146 		}
5147 
5148 		// "Let buffer be the empty string."
5149 		var buffer = "";
5150 
5151 		// "If non-breaking start is true, let repeated pair be U+00A0 U+0020.
5152 		// Otherwise, let it be U+0020 U+00A0."
5153 		var repeatedPair;
5154 		if (nonBreakingStart) {
5155 			repeatedPair = "\xa0 ";
5156 		} else {
5157 			repeatedPair = " \xa0";
5158 		}
5159 
5160 		// "While n is greater than three, append repeated pair to buffer and
5161 		// subtract two from n."
5162 		while (n > 3) {
5163 			buffer += repeatedPair;
5164 			n -= 2;
5165 		}
5166 
5167 		// "If n is three, append a three-element string to buffer depending on
5168 		// non-breaking start and non-breaking end:"
5169 		if (n == 3) {
5170 			buffer += !nonBreakingStart && !nonBreakingEnd ? " \xa0 " : nonBreakingStart && !nonBreakingEnd ? "\xa0\xa0 " : !nonBreakingStart && nonBreakingEnd ? " \xa0\xa0" : nonBreakingStart && nonBreakingEnd ? "\xa0 \xa0" : "impossible";
5171 
5172 			// "Otherwise, append a two-element string to buffer depending on
5173 			// non-breaking start and non-breaking end:"
5174 		} else {
5175 			buffer += !nonBreakingStart && !nonBreakingEnd ? "\xa0 " : nonBreakingStart && !nonBreakingEnd ? "\xa0 " : !nonBreakingStart && nonBreakingEnd ? " \xa0" : nonBreakingStart && nonBreakingEnd ? "\xa0\xa0" : "impossible";
5176 		}
5177 
5178 		// "Return buffer."
5179 		return buffer;
5180 	}
5181 
5182 	function canonicalizeWhitespace(node, offset) {
5183 		// "If node is neither editable nor an editing host, abort these steps."
5184 		if (!isEditable(node) && !isEditingHost(node)) {
5185 			return;
5186 		}
5187 
5188 		// "Let start node equal node and let start offset equal offset."
5189 		var startNode = node;
5190 		var startOffset = offset;
5191 
5192 		// "Repeat the following steps:"
5193 		while (true) {
5194 			// "If start node has a child in the same editing host with index start
5195 			// offset minus one, set start node to that child, then set start
5196 			// offset to start node's length."
5197 			if (0 <= startOffset - 1 && inSameEditingHost(startNode, startNode.childNodes[startOffset - 1])) {
5198 				startNode = startNode.childNodes[startOffset - 1];
5199 				startOffset = getNodeLength(startNode);
5200 
5201 				// "Otherwise, if start offset is zero and start node does not follow a
5202 				// line break and start node's parent is in the same editing host, set
5203 5204 				// start offset to start node's index, then set start node to its
5205 				// parent."
5206 			} else if (startOffset == 0 && !followsLineBreak(startNode) && inSameEditingHost(startNode, startNode.parentNode)) {
5207 				startOffset = Dom.getIndexInParent(startNode);
5208 				startNode = startNode.parentNode;
5209 
5210 				// "Otherwise, if start node is a Text node and its parent's resolved
5211 				// value for "white-space" is neither "pre" nor "pre-wrap" and start
5212 				// offset is not zero and the (start offset − 1)st element of start
5213 				// node's data is a space (0x0020) or non-breaking space (0x00A0),
5214 				// subtract one from start offset."
5215 			} else if (startNode.nodeType == $_.Node.TEXT_NODE && jQuery.inArray($_.getComputedStyle(startNode.parentNode).whiteSpace, ["pre", "pre-wrap"]) == -1 && startOffset != 0 && /[ \xa0]/.test(startNode.data[startOffset - 1])) {
5216 				startOffset--;
5217 
5218 				// "Otherwise, break from this loop."
5219 			} else {
5220 				break;
5221 			}
5222 		}
5223 
5224 		// "Let end node equal start node and end offset equal start offset."
5225 		var endNode = startNode;
5226 		var endOffset = startOffset;
5227 
5228 		// "Let length equal zero."
5229 		var length = 0;
5230 
5231 		// "Let follows space be false."
5232 		var followsSpace = false;
5233 
5234 		// "Repeat the following steps:"
5235 		while (true) {
5236 			// "If end node has a child in the same editing host with index end
5237 			// offset, set end node to that child, then set end offset to zero."
5238 			if (endOffset < endNode.childNodes.length && inSameEditingHost(endNode, endNode.childNodes[endOffset])) {
5239 				endNode = endNode.childNodes[endOffset];
5240 				endOffset = 0;
5241 
5242 				// "Otherwise, if end offset is end node's length and end node does not
5243 				// precede a line break and end node's parent is in the same editing
5244 				// host, set end offset to one plus end node's index, then set end node
5245 				// to its parent."
5246 			} else if (endOffset == getNodeLength(endNode) && !precedesLineBreak(endNode) && inSameEditingHost(endNode, endNode.parentNode)) {
5247 				endOffset = 1 + Dom.getIndexInParent(endNode);
5248 				endNode = endNode.parentNode;
5249 
5250 				// "Otherwise, if end node is a Text node and its parent's resolved
5251 				// value for "white-space" is neither "pre" nor "pre-wrap" and end
5252 				// offset is not end node's length and the end offsetth element of
5253 				// end node's data is a space (0x0020) or non-breaking space (0x00A0):"
5254 			} else if (endNode.nodeType == $_.Node.TEXT_NODE && jQuery.inArray($_.getComputedStyle(endNode.parentNode).whiteSpace, ["pre", "pre-wrap"]) == -1 && endOffset != getNodeLength(endNode) && /[ \xa0]/.test(endNode.data[endOffset])) {
5255 				// "If follows space is true and the end offsetth element of end
5256 				// node's data is a space (0x0020), call deleteData(end offset, 1)
5257 				// on end node, then continue this loop from the beginning."
5258 				if (followsSpace && " " == endNode.data[endOffset]) {
5259 					endNode.deleteData(endOffset, 1);
5260 					continue;
5261 				}
5262 
5263 				// "Set follows space to true if the end offsetth element of end
5264 				// node's data is a space (0x0020), false otherwise."
5265 				followsSpace = " " == endNode.data[endOffset];
5266 
5267 				// "Add one to end offset."
5268 				endOffset++;
5269 
5270 				// "Add one to length."
5271 				length++;
5272 
5273 				// "Otherwise, break from this loop."
5274 			} else {
5275 				break;
5276 			}
5277 		}
5278 
5279 		// "Let replacement whitespace be the canonical space sequence of length
5280 		// length. non-breaking start is true if start offset is zero and start
5281 		// node follows a line break, and false otherwise. non-breaking end is true
5282 		// if end offset is end node's length and end node precedes a line break,
5283 		// and false otherwise."
5284 		var replacementWhitespace = canonicalSpaceSequence(length, startOffset == 0 && followsLineBreak(startNode), endOffset == getNodeLength(endNode) && precedesLineBreak(endNode));
5285 
5286 		// "While (start node, start offset) is before (end node, end offset):"
5287 		while (getPosition(startNode, startOffset, endNode, endOffset) == "before") {
5288 			// "If start node has a child with index start offset, set start node
5289 			// to that child, then set start offset to zero."
5290 			if (startOffset < startNode.childNodes.length) {
5291 				startNode = startNode.childNodes[startOffset];
5292 				startOffset = 0;
5293 
5294 				// "Otherwise, if start node is not a Text node or if start offset is
5295 				// start node's length, set start offset to one plus start node's
5296 				// index, then set start node to its parent."
5297 			} else if (startNode.nodeType != $_.Node.TEXT_NODE || startOffset == getNodeLength(startNode)) {
5298 				startOffset = 1 + Dom.getIndexInParent(startNode);
5299 				startNode = startNode.parentNode;
5300 
5301 				// "Otherwise:"
5302 			} else {
5303 				// "Remove the first element from replacement whitespace, and let
5304 				// element be that element."
5305 				var element = replacementWhitespace[0];
5306 				replacementWhitespace = replacementWhitespace.slice(1);
5307 
5308 				// "If element is not the same as the start offsetth element of
5309 				// start node's data:"
5310 				if (element != startNode.data[startOffset]) {
5311 					// "Call insertData(start offset, element) on start node."
5312 					startNode.insertData(startOffset, element);
5313 
5314 					// "Call deleteData(start offset + 1, 1) on start node."
5315 					startNode.deleteData(startOffset + 1, 1);
5316 				}
5317 
5318 				// "Add one to start offset."
5319 				startOffset++;
5320 			}
5321 		}
5322 	}
5323 
5324 	//@}
5325 	///// Deleting the contents of a range /////
5326 	//@{
5327 
5328 	function deleteContents(arg1, arg2, arg3, arg4, arg5) {
5329 		// We accept several different calling conventions:
5330 		//
5331 		// 1) A single argument, which is a range.
5332 		//
5333 		// 2) Two arguments, the first being a range and the second flags.
5334 		//
5335 		// 3) Four arguments, the start and end of a range.
5336 		//
5337 		// 4) Five arguments, the start and end of a range plus flags.
5338 5339 		//
5340 		// The flags argument is a dictionary that can have up to two keys,
5341 		// blockMerging and stripWrappers, whose corresponding values are
5342 		// interpreted as boolean.  E.g., {stripWrappers: false}.
5343 		var range;
5344 		var flags = {};
5345 		var i;
5346 
5347 		if (arguments.length < 3) {
5348 			range = arg1;
5349 		} else {
5350 			range = Aloha.createRange();
5351 			range.setStart(arg1, arg2);
5352 			range.setEnd(arg3, arg4);
5353 		}
5354 		if (arguments.length == 2) {
5355 			flags = arg2;
5356 		}
5357 		if (arguments.length == 5) {
5358 			flags = arg5;
5359 		}
5360 
5361 		var blockMerging = null != flags.blockMerging ? !!flags.blockMerging : true;
5362 		var stripWrappers = null != flags.stripWrappers ? !!flags.stripWrappers : true;
5363 
5364 		// "If range is null, abort these steps and do nothing."
5365 		if (!range) {
5366 			return;
5367 		}
5368 
5369 		// "Let start node, start offset, end node, and end offset be range's start
5370 		// and end nodes and offsets."
5371 		var startNode = range.startContainer;
5372 		var startOffset = range.startOffset;
5373 		var endNode = range.endContainer;
5374 		var endOffset = range.endOffset;
5375 		var referenceNode;
5376 
5377 		// "While start node has at least one child:"
5378 		while (startNode.hasChildNodes()) {
5379 			// "If start offset is start node's length, and start node's parent is
5380 			// in the same editing host, and start node is an inline node, set
5381 			// start offset to one plus the index of start node, then set start
5382 			// node to its parent and continue this loop from the beginning."
5383 			if (startOffset == getNodeLength(startNode) && inSameEditingHost(startNode, startNode.parentNode) && isInlineNode(startNode)) {
5384 				startOffset = 1 + Dom.getIndexInParent(startNode);
5385 				startNode = startNode.parentNode;
5386 				continue;
5387 			}
5388 
5389 			// "If start offset is start node's length, break from this loop."
5390 			if (startOffset == getNodeLength(startNode)) {
5391 				break;
5392 			}
5393 
5394 			// "Let reference node be the child of start node with index equal to
5395 			// start offset."
5396 			referenceNode = startNode.childNodes[startOffset];
5397 
5398 			// "If reference node is a block node or an Element with no children,
5399 			// or is neither an Element nor a Text node, break from this loop."
5400 			if (isBlockNode(referenceNode) || (referenceNode.nodeType == $_.Node.ELEMENT_NODE && !referenceNode.hasChildNodes()) || (referenceNode.nodeType != $_.Node.ELEMENT_NODE && referenceNode.nodeType != $_.Node.TEXT_NODE)) {
5401 				break;
5402 			}
5403 
5404 			// "Set start node to reference node and start offset to 0."
5405 			startNode = referenceNode;
5406 			startOffset = 0;
5407 		}
5408 
5409 		// "While end node has at least one child:"
5410 		while (endNode.hasChildNodes()) {
5411 			// "If end offset is 0, and end node's parent is in the same editing
5412 			// host, and end node is an inline node, set end offset to the index of
5413 			// end node, then set end node to its parent and continue this loop
5414 			// from the beginning."
5415 			if (endOffset == 0 && inSameEditingHost(endNode, endNode.parentNode) && isInlineNode(endNode)) {
5416 				endOffset = Dom.getIndexInParent(endNode);
5417 				endNode = endNode.parentNode;
5418 				continue;
5419 			}
5420 
5421 			// "If end offset is 0, break from this loop."
5422 			if (endOffset == 0) {
5423 				break;
5424 			}
5425 
5426 			// "Let reference node be the child of end node with index equal to end
5427 			// offset minus one."
5428 			referenceNode = endNode.childNodes[endOffset - 1];
5429 
5430 			// "If reference node is a block node or an Element with no children,
5431 			// or is neither an Element nor a Text node, break from this loop."
5432 			if (isBlockNode(referenceNode) || (referenceNode.nodeType == $_.Node.ELEMENT_NODE && !referenceNode.hasChildNodes()) || (referenceNode.nodeType != $_.Node.ELEMENT_NODE && referenceNode.nodeType != $_.Node.TEXT_NODE)) {
5433 				break;
5434 			}
5435 
5436 			// "Set end node to reference node and end offset to the length of
5437 			// reference node."
5438 			endNode = referenceNode;
5439 			endOffset = getNodeLength(referenceNode);
5440 		}
5441 
5442 		// "If (end node, end offset) is not after (start node, start offset), set
5443 		// range's end to its start and abort these steps."
5444 		if (getPosition(endNode, endOffset, startNode, startOffset) !== "after") {
5445 			range.setEnd(range.startContainer, range.startOffset);
5446 			return range;
5447 		}
5448 
5449 		// "If start node is a Text node and start offset is 0, set start offset to
5450 		// the index of start node, then set start node to its parent."
5451 		// Commented out for unknown reason
5452 		//if (startNode.nodeType == $_.Node.TEXT_NODE && startOffset == 0 && startNode != endNode) {
5453 		//		startOffset = Dom.getIndexInParent(startNode);
5454 		//		startNode = startNode.parentNode;
5455 		//}
5456 
5457 		// "If end node is a Text node and end offset is its length, set end offset
5458 		// to one plus the index of end node, then set end node to its parent."
5459 		if (endNode.nodeType == $_.Node.TEXT_NODE && endOffset == getNodeLength(endNode) && startNode != endNode) {
5460 			endOffset = 1 + Dom.getIndexInParent(endNode);
5461 			endNode = endNode.parentNode;
5462 		}
5463 
5464 		// "Set range's start to (start node, start offset) and its end to (end
5465 		// node, end offset)."
5466 		range.setStart(startNode, startOffset);
5467 		range.setEnd(endNode, endOffset);
5468 
5469 		// "Let start block be the start node of range."
5470 		var startBlock = range.startContainer;
5471 
5472 		// "While start block's parent is in the same editing host and start block
5473 		// is an inline node, set start block to its parent."
5474 		while (inSameEditingHost(startBlock, startBlock.parentNode) && isInlineNode(startBlock)) {
5475 			startBlock = startBlock.parentNode;
5476 		}
5477 
5478 		// "If start block is neither a block node nor an editing host, or "span"
5479 		// is not an allowed child of start block, or start block is a td or th,
5480 		// set start block to null."
5481 		if ((!isBlockNode(startBlock) && !isEditingHost(startBlock)) || !isAllowedChild("span", startBlock) || isHtmlElementInArray(startBlock, ["td", "th"])) {
5482 			startBlock = null;
5483 		}
5484 
5485 		// "Let end block be the end node of range."
5486 		var endBlock = range.endContainer;
5487 
5488 		// "While end block's parent is in the same editing host and end block is
5489 		// an inline node, set end block to its parent."
5490 		while (inSameEditingHost(endBlock, endBlock.parentNode) && isInlineNode(endBlock)) {
5491 			endBlock = endBlock.parentNode;
5492 		}
5493 
5494 		// "If end block is neither a block node nor an editing host, or "span" is
5495 		// not an allowed child of end block, or end block is a td or th, set end
5496 		// block to null."
5497 		if ((!isBlockNode(endBlock) && !isEditingHost(endBlock)) || !isAllowedChild("span", endBlock) || isHtmlElementInArray(endBlock, ["td", "th"])) {
5498 			endBlock = null;
5499 		}
5500 
5501 		// "Record current states and values, and let overrides be the result."
5502 		var overrides = recordCurrentStatesAndValues(range);
5503 		var parent_;
5504 		// "If start node and end node are the same, and start node is an editable
5505 		// Text node:"
5506 		if (startNode == endNode && isEditable(startNode) && startNode.nodeType == $_.Node.TEXT_NODE) {
5507 			// "Let parent be the parent of node."
5508 			parent_ = startNode.parentNode;
5509 
5510 			// "Call deleteData(start offset, end offset − start offset) on start
5511 			// node."
5512 			startNode.deleteData(startOffset, endOffset - startOffset);
5513 
5514 			// if deleting the text moved two spaces together, we replace the left one by a  , which makes the two spaces a visible
5515 			// two space sequence
5516 			if (startOffset > 0 && startNode.data.substr(startOffset - 1, 1) === ' ' && startOffset < startNode.data.length && startNode.data.substr(startOffset, 1) === ' ') {
5517 				startNode.replaceData(startOffset - 1, 1, '\xa0');
5518 			}
5519 
5520 			// "Canonicalize whitespace at (start node, start offset)."
5521 			canonicalizeWhitespace(startNode, startOffset);
5522 
5523 			// "Set range's end to its start."
5524 			// Ok, also set the range's start to its start, because modifying the text
5525 			// might have somehow corrupted the range
5526 5527 			range.setStart(range.startContainer, range.startOffset);
5528 			range.setEnd(range.startContainer, range.startOffset);
5529 
5530 			// "Restore states and values from overrides."
5531 			restoreStatesAndValues(overrides, range);
5532 
5533 			// "If parent is editable or an editing host, is not an inline node,
5534 			// and has no children, call createElement("br") on the context object
5535 			// and append the result as the last child of parent."
5536 			// only do this, if the offsetHeight is 0
5537 			if ((isEditable(parent_) || isEditingHost(parent_)) && !isInlineNode(parent_)) {
5538 				ensureContainerEditable(parent_);
5539 			}
5540 
5541 			// "Abort these steps."
5542 			return range;
5543 		}
5544 
5545 		// "If start node is an editable Text node, call deleteData() on it, with
5546 		// start offset as the first argument and (length of start node − start
5547 		// offset) as the second argument."
5548 		if (isEditable(startNode) && startNode.nodeType == $_.Node.TEXT_NODE) {
5549 			startNode.deleteData(startOffset, getNodeLength(startNode) - startOffset);
5550 		}
5551 
5552 		// "Let node list be a list of nodes, initially empty."
5553 		//
5554 		// "For each node contained in range, append node to node list if the last
5555 		// member of node list (if any) is not an ancestor of node; node is
5556 		// editable; and node is not a thead, tbody, tfoot, tr, th, or td."
5557 		var nodeList = getContainedNodes(
5558 			range,
5559 			function (node) {
5560 				return isEditable(node) && !isHtmlElementInArray(node, ["thead", "tbody", "tfoot", "tr", "th", "td"]);
5561 			}
5562 		);
5563 
5564 		// "For each node in node list:"
5565 		for (i = 0; i < nodeList.length; i++) {
5566 			var node = nodeList[i];
5567 
5568 			// "Let parent be the parent of node."
5569 			parent_ = node.parentNode;
5570 
5571 			// "Remove node from parent."
5572 			parent_.removeChild(node);
5573 
5574 			// "If strip wrappers is true or parent is not an ancestor container of
5575 			// start node, while parent is an editable inline node with length 0,
5576 			// let grandparent be the parent of parent, then remove parent from
5577 			// grandparent, then set parent to grandparent."
5578 			if (stripWrappers || (!isAncestor(parent_, startNode) && parent_ != startNode)) {
5579 				while (isEditable(parent_) && isInlineNode(parent_) && getNodeLength(parent_) == 0) {
5580 					var grandparent = parent_.parentNode;
5581 					grandparent.removeChild(parent_);
5582 					parent_ = grandparent;
5583 				}
5584 			}
5585 
5586 			// "If parent is editable or an editing host, is not an inline node,
5587 			// and has no children, call createElement("br") on the context object
5588 			// and append the result as the last child of parent."
5589 			// only do this, if the offsetHeight is 0
5590 			if ((isEditable(parent_) || isEditingHost(parent_)) && !isInlineNode(parent_)) {
5591 				ensureContainerEditable(parent_);
5592 			}
5593 		}
5594 
5595 		// "If end node is an editable Text node, call deleteData(0, end offset) on
5596 		// it."
5597 		if (isEditable(endNode) && endNode.nodeType == $_.Node.TEXT_NODE) {
5598 			endNode.deleteData(0, endOffset);
5599 		}
5600 
5601 		// "Canonicalize whitespace at range's start."
5602 		canonicalizeWhitespace(range.startContainer, range.startOffset);
5603 
5604 		// "Canonicalize whitespace at range's end."
5605 		canonicalizeWhitespace(range.endContainer, range.endOffset);
5606 
5607 		// A reference to the position where a node is removed.
5608 		var pos;
5609 
5610 		// "If block merging is false, or start block or end block is null, or
5611 		// start block is not in the same editing host as end block, or start block
5612 		// and end block are the same:"
5613 		if (!blockMerging || !startBlock || !endBlock || !inSameEditingHost(startBlock, endBlock) || startBlock == endBlock) {
5614 			// "Set range's end to its start."
5615 			range.setEnd(range.startContainer, range.startOffset);
5616 
5617 			// Calling delete on the give markup:
5618 			// <editable><block><br>[]</block></editable>
5619 			// should result in:
5620 			// <editable>[]</editable>
5621 			var block = startBlock || endBlock;
5622 			if (isEmptyOnlyChildOfEditingHost(block)) {
5623 				pos = removeNode(block);
5624 				range.setStart(pos.node, pos.offset);
5625 				range.setEnd(pos.node, pos.offset);
5626 			}
5627 
5628 			// "Restore states and values from overrides."
5629 			restoreStatesAndValues(overrides, range);
5630 
5631 			// "Abort these steps."
5632 			return range;
5633 		}
5634 
5635 		// "If start block has one child, which is a collapsed block prop, remove
5636 		// its child from it."
5637 		if (startBlock.children.length == 1 && isCollapsedBlockProp(startBlock.firstChild)) {
5638 			startBlock.removeChild(startBlock.firstChild);
5639 		}
5640 
5641 		// "If end block has one child, which is a collapsed block prop, remove its
5642 		// child from it."
5643 		if (endBlock.children.length == 1 && isCollapsedBlockProp(endBlock.firstChild)) {
5644 			endBlock.removeChild(endBlock.firstChild);
5645 		}
5646 
5647 		var values;
5648 		// "If start block is an ancestor of end block:"
5649 		if (isAncestor(startBlock, endBlock)) {
5650 			// "Let reference node be end block."
5651 			referenceNode = endBlock;
5652 
5653 			// "While reference node is not a child of start block, set reference
5654 			// node to its parent."
5655 			while (referenceNode.parentNode != startBlock) {
5656 				referenceNode = referenceNode.parentNode;
5657 			}
5658 
5659 			// "Set the start and end of range to (start block, index of reference
5660 			// node)."
5661 			range.setStart(startBlock, Dom.getIndexInParent(referenceNode));
5662 			range.setEnd(startBlock, Dom.getIndexInParent(referenceNode));
5663 
5664 			// "If end block has no children:"
5665 			if (!endBlock.hasChildNodes()) {
5666 				// "While end block is editable and is the only child of its parent
5667 				// and is not a child of start block, let parent equal end block,
5668 				// then remove end block from parent, then set end block to
5669 				// parent."
5670 				while (isEditable(endBlock) && endBlock.parentNode.childNodes.length == 1 && endBlock.parentNode != startBlock) {
5671 					parent_ = endBlock;
5672 					parent_.removeChild(endBlock);
5673 					endBlock = parent_;
5674 				}
5675 
5676 				// "If end block is editable and is not an inline node, and its
5677 				// previousSibling and nextSibling are both inline nodes, call
5678 				// createElement("br") on the context object and insert it into end
5679 				// block's parent immediately after end block."
5680 
5681 				if (isEditable(endBlock) && !isInlineNode(endBlock) && isInlineNode(endBlock.previousSibling) && isInlineNode(endBlock.nextSibling)) {
5682 					endBlock.parentNode.insertBefore(document.createElement("br"), endBlock.nextSibling);
5683 				}
5684 
5685 				// "If end block is editable, remove it from its parent."
5686 5687 				if (isEditable(endBlock)) {
5688 					endBlock.parentNode.removeChild(endBlock);
5689 				}
5690 
5691 				// "Restore states and values from overrides."
5692 				restoreStatesAndValues(overrides, range);
5693 
5694 				// "Abort these steps."
5695 				return range;
5696 			}
5697 
5698 			// "If end block's firstChild is not an inline node, restore states and
5699 			// values from overrides, then abort these steps."
5700 			if (!isInlineNode(endBlock.firstChild)) {
5701 				restoreStatesAndValues(overrides, range);
5702 				return range;
5703 			}
5704 
5705 			// "Let children be a list of nodes, initially empty."
5706 			var children = [];
5707 
5708 			// "Append the first child of end block to children."
5709 			children.push(endBlock.firstChild);
5710 
5711 			// "While children's last member is not a br, and children's last
5712 			// member's nextSibling is an inline node, append children's last
5713 			// member's nextSibling to children."
5714 			while (!isNamedHtmlElement(children[children.length - 1], "br") && isInlineNode(children[children.length - 1].nextSibling)) {
5715 				children.push(children[children.length - 1].nextSibling);
5716 			}
5717 
5718 			// "Record the values of children, and let values be the result."
5719 			values = recordValues(children);
5720 
5721 			// "While children's first member's parent is not start block, split
5722 			// the parent of children."
5723 			while (children[0].parentNode != startBlock) {
5724 				splitParent(children, range);
5725 			}
5726 
5727 			// "If children's first member's previousSibling is an editable br,
5728 			// remove that br from its parent."
5729 			if (isEditable(children[0].previousSibling) && isNamedHtmlElement(children[0].previousSibling, "br")) {
5730 				children[0].parentNode.removeChild(children[0].previousSibling);
5731 			}
5732 
5733 			// "Otherwise, if start block is a descendant of end block:"
5734 		} else if (isDescendant(startBlock, endBlock)) {
5735 			// "Set the start and end of range to (start block, length of start
5736 			// block)."
5737 			range.setStart(startBlock, getNodeLength(startBlock));
5738 			range.setEnd(startBlock, getNodeLength(startBlock));
5739 
5740 			// "Let reference node be start block."
5741 			referenceNode = startBlock;
5742 
5743 			// "While reference node is not a child of end block, set reference
5744 			// node to its parent."
5745 			while (referenceNode.parentNode != endBlock) {
5746 				referenceNode = referenceNode.parentNode;
5747 			}
5748 
5749 			// "If reference node's nextSibling is an inline node and start block's
5750 			// lastChild is a br, remove start block's lastChild from it."
5751 			if (isInlineNode(referenceNode.nextSibling) && isNamedHtmlElement(startBlock.lastChild, "br")) {
5752 				startBlock.removeChild(startBlock.lastChild);
5753 			}
5754 
5755 			// "Let nodes to move be a list of nodes, initially empty."
5756 			var nodesToMove = [];
5757 
5758 			// "If reference node's nextSibling is neither null nor a br nor a
5759 			// block node, append it to nodes to move."
5760 			if (referenceNode.nextSibling && !isNamedHtmlElement(referenceNode.nextSibling, "br") && !isBlockNode(referenceNode.nextSibling)) {
5761 				nodesToMove.push(referenceNode.nextSibling);
5762 			}
5763 
5764 			// "While nodes to move is nonempty and its last member's nextSibling
5765 			// is neither null nor a br nor a block node, append it to nodes to
5766 			// move."
5767 			if (nodesToMove.length && nodesToMove[nodesToMove.length - 1].nextSibling && !isNamedHtmlElement(nodesToMove[nodesToMove.length - 1].nextSibling, "br") && !isBlockNode(nodesToMove[nodesToMove.length - 1].nextSibling)) {
5768 				nodesToMove.push(nodesToMove[nodesToMove.length - 1].nextSibling);
5769 			}
5770 
5771 			// "Record the values of nodes to move, and let values be the result."
5772 			values = recordValues(nodesToMove);
5773 
5774 			// "For each node in nodes to move, append node as the last child of
5775 			// start block, preserving ranges."
5776 			$_(nodesToMove).forEach(function (node) {
5777 				movePreservingRanges(node, startBlock, -1, range);
5778 			});
5779 
5780 			// "If the nextSibling of reference node is a br, remove it from its
5781 			// parent."
5782 			if (isNamedHtmlElement(referenceNode.nextSibling, "br")) {
5783 				referenceNode.parentNode.removeChild(referenceNode.nextSibling);
5784 			}
5785 
5786 			// "Otherwise:"
5787 		} else {
5788 			// "Set the start and end of range to (start block, length of start
5789 			// block)."
5790 			range.setStart(startBlock, getNodeLength(startBlock));
5791 			range.setEnd(startBlock, getNodeLength(startBlock));
5792 
5793 			// "If end block's firstChild is an inline node and start block's
5794 			// lastChild is a br, remove start block's lastChild from it."
5795 			if (isInlineNode(endBlock.firstChild) && isNamedHtmlElement(startBlock.lastChild, "br")) {
5796 				startBlock.removeChild(startBlock.lastChild);
5797 			}
5798 
5799 			// "Record the values of end block's children, and let values be the
5800 			// result."
5801 			values = recordValues([].slice.call(toArray(endBlock.childNodes)));
5802 
5803 			// "While end block has children, append the first child of end block
5804 			// to start block, preserving ranges."
5805 			while (endBlock.hasChildNodes()) {
5806 				movePreservingRanges(endBlock.firstChild, startBlock, -1, range);
5807 			}
5808 
5809 			// "While end block has no children, let parent be the parent of end
5810 			// block, then remove end block from parent, then set end block to
5811 			// parent."
5812 			while (!endBlock.hasChildNodes()) {
5813 				parent_ = endBlock.parentNode;
5814 				parent_.removeChild(endBlock);
5815 				endBlock = parent_;
5816 			}
5817 		}
5818 
5819 		// "Restore the values from values."
5820 		restoreValues(values, range);
5821 
5822 		// Because otherwise calling deleteContents() with the given selection:
5823 		//
5824 		// <editable><block>[foo</block><block>bar]</block></editable>
5825 5826 		//
5827 		// would result in:
5828 		//
5829 		// <editable><block>[]<br /></block></editable>
5830 		//
5831 		// instead of:
5832 		//
5833 		// <editable>[]</editable>
5834 		//
5835 		// Therefore, the below makes it possible to completely empty contents
5836 		// of editing hosts via operations like CTRL+A, DEL.
5837 		//
5838 		// If startBlock is empty, and startBlock is the immediate and only
5839 		// child of its parent editing host, then remove startBlock and collapse
5840 		// the selection at the beginning of the editing post.
5841 		if (isEmptyOnlyChildOfEditingHost(startBlock)) {
5842 			pos = removeNode(startBlock);
5843 			range.setStart(pos.node, pos.offset);
5844 			range.setEnd(pos.node, pos.offset);
5845 			startBlock = pos.node;
5846 		}
5847 
5848 		// "If start block has no children, call createElement("br") on the context
5849 		// object and append the result as the last child of start block."
5850 		ensureContainerEditable(startBlock);
5851 
5852 		// "Restore states and values from overrides."
5853 		restoreStatesAndValues(overrides, range);
5854 
5855 		return range;
5856 	}
5857 
5858 	// "To remove a node node while preserving its descendants, split the parent of
5859 	// node's children if it has any. If it has no children, instead remove it from
5860 	// its parent."
5861 	function removePreservingDescendants(node, range) {
5862 		if (node.hasChildNodes()) {
5863 			splitParent([].slice.call(toArray(node.childNodes)), range);
5864 		} else {
5865 			node.parentNode.removeChild(node);
5866 		}
5867 	}
5868 
5869 	//@}
5870 	///// Indenting and outdenting /////
5871 	//@{
5872 
5873 	function cleanLists(node, range) {
5874 		// remove any whitespace nodes around list nodes
5875 		if (node) {
5876 			jQuery(node).find('ul,ol,li').each(function () {
5877 				jQuery(this).contents().each(function () {
5878 					if (isWhitespaceNode(this)) {
5879 						var index = Dom.getIndexInParent(this);
5880 
5881 						// if the range points to somewhere behind the removed text node, we reduce the offset
5882 						if (range.startContainer === this.parentNode && range.startOffset > index) {
5883 							range.startOffset--;
5884 						} else if (range.startContainer === this) {
5885 							// the range starts in the removed text node, let it start right before
5886 							range.startContainer = this.parentNode;
5887 							range.startOffset = index;
5888 						}
5889 						// same thing for end of the range
5890 						if (range.endContainer === this.parentNode && range.endOffset > index) {
5891 							range.endOffset--;
5892 						} else if (range.endContainer === this) {
5893 							range.endContainer = this.parentNode;
5894 							range.endOffset = index;
5895 						}
5896 						// finally remove the whitespace node
5897 						jQuery(this).remove();
5898 					}
5899 				});
5900 			});
5901 		}
5902 	}
5903 
5904 
5905 	//@}
5906 	///// Indenting and outdenting /////
5907 	//@{
5908 
5909 	function indentNodes(nodeList, range) {
5910 		// "If node list is empty, do nothing and abort these steps."
5911 		if (!nodeList.length) {
5912 			return;
5913 		}
5914 
5915 		// "Let first node be the first member of node list."
5916 		var firstNode = nodeList[0];
5917 
5918 		// "If first node's parent is an ol or ul:"
5919 		if (isHtmlElementInArray(firstNode.parentNode, ["OL", "UL"])) {
5920 			// "Let tag be the local name of the parent of first node."
5921 			var tag = firstNode.parentNode.tagName;
5922 
5923 			// "Wrap node list, with sibling criteria returning true for an HTML
5924 			// element with local name tag and false otherwise, and new parent
5925 			// instructions returning the result of calling createElement(tag) on
5926 			// the ownerDocument of first node."
5927 			wrap(
5928 				nodeList,
5929 				function (node) {
5930 					return isHtmlElement_obsolete(node, tag);
5931 				},
5932 				function () {
5933 					return firstNode.ownerDocument.createElement(tag);
5934 				},
5935 				range
5936 			);
5937 
5938 			// "Abort these steps."
5939 			return;
5940 		}
5941 
5942 		// "Wrap node list, with sibling criteria returning true for a simple
5943 		// indentation element and false otherwise, and new parent instructions
5944 		// returning the result of calling createElement("blockquote") on the
5945 		// ownerDocument of first node. Let new parent be the result."
5946 		var newParent = wrap(
5947 			nodeList,
5948 			function (node) {
5949 				return isSimpleIndentationElement(node);
5950 			},
5951 			function () {
5952 				return firstNode.ownerDocument.createElement("blockquote");
5953 			},
5954 			range
5955 		);
5956 
5957 		// "Fix disallowed ancestors of new parent."
5958 		fixDisallowedAncestors(newParent, range);
5959 	}
5960 
5961 	function outdentNode(node, range) {
5962 		// "If node is not editable, abort these steps."
5963 		if (!isEditable(node)) {
5964 			return;
5965 		}
5966 
5967 		// "If node is a simple indentation element, remove node, preserving its
5968 		// descendants.  Then abort these steps."
5969 		if (isSimpleIndentationElement(node)) {
5970 			removePreservingDescendants(node, range);
5971 			return;
5972 		}
5973 
5974 		// "If node is an indentation element:"
5975 		if (isIndentationElement(node)) {
5976 			// "Unset the class and dir attributes of node, if any."
5977 			node.removeAttribute("class");
5978 			node.removeAttribute("dir");
5979 
5980 			// "Unset the margin, padding, and border CSS properties of node."
5981 			node.style.margin = "";
5982 			node.style.padding = "";
5983 			node.style.border = "";
5984 			if (node.getAttribute("style") == "") {
5985 				node.removeAttribute("style");
5986 			}
5987 
5988 			// "Set the tag name of node to "div"."
5989 			setTagName(node, "div", range);
5990 
5991 			// "Abort these steps."
5992 			return;
5993 		}
5994 
5995 		// "Let current ancestor be node's parent."
5996 		var currentAncestor = node.parentNode;
5997 
5998 		// "Let ancestor list be a list of nodes, initially empty."
5999 		var ancestorList = [];
6000 
6001 		// "While current ancestor is an editable Element that is neither a simple
6002 		// indentation element nor an ol nor a ul, append current ancestor to
6003 		// ancestor list and then set current ancestor to its parent."
6004 		while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !isSimpleIndentationElement(currentAncestor) && !isHtmlElementInArray(currentAncestor, ["ol", "ul"])) {
6005 			ancestorList.push(currentAncestor);
6006 			currentAncestor = currentAncestor.parentNode;
6007 		}
6008 
6009 		// "If current ancestor is not an editable simple indentation element:"
6010 		if (!isEditable(currentAncestor) || !isSimpleIndentationElement(currentAncestor)) {
6011 			// "Let current ancestor be node's parent."
6012 			currentAncestor = node.parentNode;
6013 
6014 			// "Let ancestor list be the empty list."
6015 			ancestorList = [];
6016 
6017 			// "While current ancestor is an editable Element that is neither an
6018 			// indentation element nor an ol nor a ul, append current ancestor to
6019 			// ancestor list and then set current ancestor to its parent."
6020 			while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !isIndentationElement(currentAncestor) && !isHtmlElementInArray(currentAncestor, ["ol", "ul"])) {
6021 				ancestorList.push(currentAncestor);
6022 				currentAncestor = currentAncestor.parentNode;
6023 			}
6024 		}
6025 
6026 		// "If node is an ol or ul and current ancestor is not an editable
6027 		// indentation element:"
6028 		if (isHtmlElementInArray(node, ["OL", "UL"]) && (!isEditable(currentAncestor) || !isIndentationElement(currentAncestor))) {
6029 			// "Unset the reversed, start, and type attributes of node, if any are
6030 			// set."
6031 			node.removeAttribute("reversed");
6032 			node.removeAttribute("start");
6033 			node.removeAttribute("type");
6034 
6035 			// "Let children be the children of node."
6036 			var children = [].slice.call(toArray(node.childNodes));
6037 
6038 			// "If node has attributes, and its parent is not an ol or ul, set the
6039 			// tag name of node to "div"."
6040 			if (node.attributes.length && !isHtmlElementInArray(node.parentNode, ["OL", "UL"])) {
6041 				setTagName(node, "div", range);
6042 
6043 				// "Otherwise:"
6044 			} else {
6045 				// "Record the values of node's children, and let values be the
6046 				// result."
6047 				var values = recordValues([].slice.call(toArray(node.childNodes)));
6048 
6049 				// "Remove node, preserving its descendants."
6050 				removePreservingDescendants(node, range);
6051 
6052 				// "Restore the values from values."
6053 				restoreValues(values, range);
6054 6055 			}
6056 
6057 			// "Fix disallowed ancestors of each member of children."
6058 			var i;
6059 			for (i = 0; i < children.length; i++) {
6060 				fixDisallowedAncestors(children[i], range);
6061 			}
6062 
6063 			// "Abort these steps."
6064 			return;
6065 		}
6066 
6067 		// "If current ancestor is not an editable indentation element, abort these
6068 		// steps."
6069 		if (!isEditable(currentAncestor) || !isIndentationElement(currentAncestor)) {
6070 			return;
6071 		}
6072 
6073 		// "Append current ancestor to ancestor list."
6074 		ancestorList.push(currentAncestor);
6075 
6076 		// "Let original ancestor be current ancestor."
6077 		var originalAncestor = currentAncestor;
6078 
6079 		// "While ancestor list is not empty:"
6080 		while (ancestorList.length) {
6081 			// "Let current ancestor be the last member of ancestor list."
6082 			//
6083 			// "Remove the last member of ancestor list."
6084 			currentAncestor = ancestorList.pop();
6085 
6086 			// "Let target be the child of current ancestor that is equal to either
6087 			// node or the last member of ancestor list."
6088 			var target = node.parentNode == currentAncestor ? node : ancestorList[ancestorList.length - 1];
6089 
6090 			// "If target is an inline node that is not a br, and its nextSibling
6091 			// is a br, remove target's nextSibling from its parent."
6092 			if (isInlineNode(target) && !isNamedHtmlElement(target, 'BR') && isNamedHtmlElement(target.nextSibling, "BR")) {
6093 				target.parentNode.removeChild(target.nextSibling);
6094 			}
6095 
6096 			// "Let preceding siblings be the preceding siblings of target, and let
6097 			// following siblings be the following siblings of target."
6098 			var precedingSiblings = [].slice.call(toArray(currentAncestor.childNodes), 0, Dom.getIndexInParent(target));
6099 			var followingSiblings = [].slice.call(toArray(currentAncestor.childNodes), 1 + Dom.getIndexInParent(target));
6100 
6101 			// "Indent preceding siblings."
6102 			indentNodes(precedingSiblings, range);
6103 
6104 			// "Indent following siblings."
6105 			indentNodes(followingSiblings, range);
6106 		}
6107 
6108 		// "Outdent original ancestor."
6109 		outdentNode(originalAncestor, range);
6110 	}
6111 
6112 
6113 	//@}
6114 	///// Toggling lists /////
6115 	//@{
6116 
6117 	function toggleLists(tagName, range) {
6118 		// "Let mode be "disable" if the selection's list state is tag name, and
6119 		// "enable" otherwise."
6120 		var mode = getSelectionListState() == tagName ? "disable" : "enable";
6121 
6122 		tagName = tagName.toUpperCase();
6123 
6124 		// "Let other tag name be "ol" if tag name is "ul", and "ul" if tag name is
6125 		// "ol"."
6126 		var otherTagName = tagName == "OL" ? "UL" : "OL";
6127 
6128 		// "Let items be a list of all lis that are ancestor containers of the
6129 		// range's start and/or end node."
6130 		//
6131 		// It's annoying to get this in tree order using functional stuff without
6132 		// doing getDescendants(document), which is slow, so I do it imperatively.
6133 		var items = [];
6134 		(function () {
6135 			var ancestorContainer;
6136 			for (ancestorContainer = range.endContainer;
6137 				     ancestorContainer != range.commonAncestorContainer;
6138 				     ancestorContainer = ancestorContainer.parentNode) {
6139 				if (isNamedHtmlElement(ancestorContainer, "li")) {
6140 					items.unshift(ancestorContainer);
6141 				}
6142 			}
6143 			for (ancestorContainer = range.startContainer;
6144 				     ancestorContainer;
6145 				     ancestorContainer = ancestorContainer.parentNode) {
6146 				if (isNamedHtmlElement(ancestorContainer, "li")) {
6147 					items.unshift(ancestorContainer);
6148 				}
6149 			}
6150 		}());
6151 
6152 		// "For each item in items, normalize sublists of item."
6153 		$_(items).forEach(function (thisArg) {
6154 			normalizeSublists(thisArg, range);
6155 		});
6156 
6157 		// "Block-extend the range, and let new range be the result."
6158 		var newRange = blockExtend(range);
6159 
6160 		// "If mode is "enable", then let lists to convert consist of every
6161 		// editable HTML element with local name other tag name that is contained
6162 		// in new range, and for every list in lists to convert:"
6163 		if (mode == "enable") {
6164 			$_(getAllContainedNodes(newRange, function (node) {
6165 				return isEditable(node) && isHtmlElement_obsolete(node, otherTagName);
6166 			})).forEach(function (list) {
6167 				// "If list's previousSibling or nextSibling is an editable HTML
6168 				// element with local name tag name:"
6169 				if ((isEditable(list.previousSibling) && isHtmlElement_obsolete(list.previousSibling, tagName)) || (isEditable(list.nextSibling) && isHtmlElement_obsolete(list.nextSibling, tagName))) {
6170 					// "Let children be list's children."
6171 					var children = [].slice.call(toArray(list.childNodes));
6172 
6173 					// "Record the values of children, and let values be the
6174 					// result."
6175 					var values = recordValues(children);
6176 
6177 					// "Split the parent of children."
6178 					splitParent(children, range);
6179 
6180 					// "Wrap children, with sibling criteria returning true for an
6181 					// HTML element with local name tag name and false otherwise."
6182 					wrap(
6183 						children,
6184 						function (node) {
6185 							return isHtmlElement_obsolete(node, tagName);
6186 						},
6187 						function () {
6188 							return null;
6189 						},
6190 						range
6191 					);
6192 
6193 					// "Restore the values from values."
6194 					restoreValues(values, range);
6195 
6196 					// "Otherwise, set the tag name of list to tag name."
6197 				} else {
6198 					setTagName(list, tagName, range);
6199 				}
6200 			});
6201 		}
6202 
6203 		// "Let node list be a list of nodes, initially empty."
6204 		//
6205 		// "For each node node contained in new range, if node is editable; the
6206 		// last member of node list (if any) is not an ancestor of node; node
6207 		// is not an indentation element; and either node is an ol or ul, or its
6208 		// parent is an ol or ul, or it is an allowed child of "li"; then append
6209 		// node to node list."
6210 		var nodeList = getContainedNodes(newRange, function (node) {
6211 			return isEditable(node) && !isIndentationElement(node) && (isHtmlElementInArray(node, ["OL", "UL"]) || isHtmlElementInArray(node.parentNode, ["OL", "UL"]) || isAllowedChild(node, "li"));
6212 		});
6213 
6214 		// "If mode is "enable", remove from node list any ol or ul whose parent is
6215 		// not also an ol or ul."
6216 		if (mode == "enable") {
6217 			nodeList = $_(nodeList).filter(function (node) {
6218 				return !isHtmlElementInArray(node, ["ol", "ul"]) || isHtmlElementInArray(node.parentNode, ["ol", "ul"]);
6219 			});
6220 		}
6221 
6222 		// "If mode is "disable", then while node list is not empty:"
6223 		var sublist, values;
6224 
6225 		function createLi() {
6226 			return document.createElement("li");
6227 		}
6228 
6229 		function isOlUl(node) {
6230 			return isHtmlElementInArray(node, ["ol", "ul"]);
6231 		}
6232 
6233 		function makeIsElementPred(tagName) {
6234 			return function (node) {
6235 				return isHtmlElement_obsolete(node, tagName);
6236 			};
6237 		}
6238 
6239 		function makeCreateElement(tagName) {
6240 			return function () {
6241 				return document.createElement(tagName);
6242 			};
6243 		}
6244 
6245 		function makeCreateElementSublist(tagName, sublist, range) {
6246 			return function () {
6247 				// "If sublist's first member's parent is not an editable
6248 				// simple indentation element, or sublist's first member's
6249 				// parent's previousSibling is not an editable HTML element
6250 				// with local name tag name, call createElement(tag name)
6251 				// on the context object and return the result."
6252 				if (!isEditable(sublist[0].parentNode) || !isSimpleIndentationElement(sublist[0].parentNode) || !isEditable(sublist[0].parentNode.previousSibling) || !isHtmlElement_obsolete(sublist[0].parentNode.previousSibling, tagName)) {
6253 					return document.createElement(tagName);
6254 				}
6255 
6256 				// "Let list be sublist's first member's parent's
6257 				// previousSibling."
6258 				var list = sublist[0].parentNode.previousSibling;
6259 
6260 				// "Normalize sublists of list's lastChild."
6261 				normalizeSublists(list.lastChild, range);
6262 
6263 				// "If list's lastChild is not an editable HTML element
6264 				// with local name tag name, call createElement(tag name)
6265 				// on the context object, and append the result as the last
6266 				// child of list."
6267 				if (!isEditable(list.lastChild) || !isHtmlElement_obsolete(list.lastChild, tagName)) {
6268 					list.appendChild(document.createElement(tagName));
6269 				}
6270 
6271 				// "Return the last child of list."
6272 				return list.lastChild;
6273 			};
6274 		}
6275 
6276 		if (mode == "disable") {
6277 			while (nodeList.length) {
6278 				// "Let sublist be an empty list of nodes."
6279 				sublist = [];
6280 
6281 				// "Remove the first member from node list and append it to
6282 				// sublist."
6283 				sublist.push(nodeList.shift());
6284 
6285 				// "If the first member of sublist is an HTML element with local
6286 				// name tag name, outdent it and continue this loop from the
6287 				// beginning."
6288 				if (isHtmlElement_obsolete(sublist[0], tagName)) {
6289 					outdentNode(sublist[0], range);
6290 					continue;
6291 				}
6292 
6293 				// "While node list is not empty, and the first member of node list
6294 				// is the nextSibling of the last member of sublist and is not an
6295 				// HTML element with local name tag name, remove the first member
6296 				// from node list and append it to sublist."
6297 				while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isHtmlElement_obsolete(nodeList[0], tagName)) {
6298 					sublist.push(nodeList.shift());
6299 				}
6300 
6301 				// "Record the values of sublist, and let values be the result."
6302 				values = recordValues(sublist);
6303 
6304 				// "Split the parent of sublist."
6305 				splitParent(sublist, range);
6306 
6307 				// "Fix disallowed ancestors of each member of sublist."
6308 				var i;
6309 				for (i = 0; i < sublist.length; i++) {
6310 					fixDisallowedAncestors(sublist[i], range);
6311 				}
6312 
6313 				// "Restore the values from values."
6314 				restoreValues(values, range);
6315 			}
6316 
6317 			// "Otherwise, while node list is not empty:"
6318 		} else {
6319 			while (nodeList.length) {
6320 				// "Let sublist be an empty list of nodes."
6321 				sublist = [];
6322 
6323 				// "While either sublist is empty, or node list is not empty and
6324 				// its first member is the nextSibling of sublist's last member:"
6325 				while (!sublist.length || (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling)) {
6326 					// "If node list's first member is a p or div, set the tag name
6327 					// of node list's first member to "li", and append the result
6328 					// to sublist. Remove the first member from node list."
6329 					if (isHtmlElementInArray(nodeList[0], ["p", "div"])) {
6330 						sublist.push(setTagName(nodeList[0], "li", range));
6331 						nodeList.shift();
6332 
6333 						// "Otherwise, if the first member of node list is an li or ol
6334 						// or ul, remove it from node list and append it to sublist."
6335 					} else if (isHtmlElementInArray(nodeList[0], ["li", "ol", "ul"])) {
6336 						sublist.push(nodeList.shift());
6337 
6338 						// "Otherwise:"
6339 					} else {
6340 						// "Let nodes to wrap be a list of nodes, initially empty."
6341 						var nodesToWrap = [];
6342 
6343 						// "While nodes to wrap is empty, or node list is not empty
6344 						// and its first member is the nextSibling of nodes to
6345 						// wrap's last member and the first member of node list is
6346 						// an inline node and the last member of nodes to wrap is
6347 						// an inline node other than a br, remove the first member
6348 						// from node list and append it to nodes to wrap."
6349 						while (!nodesToWrap.length || (nodeList.length && nodeList[0] == nodesToWrap[nodesToWrap.length - 1].nextSibling && isInlineNode(nodeList[0]) && isInlineNode(nodesToWrap[nodesToWrap.length - 1]) && !isNamedHtmlElement(nodesToWrap[nodesToWrap.length - 1], "br"))) {
6350 							nodesToWrap.push(nodeList.shift());
6351 						}
6352 
6353 						// "Wrap nodes to wrap, with new parent instructions
6354 						// returning the result of calling createElement("li") on
6355 						// the context object. Append the result to sublist."
6356 						sublist.push(wrap(
6357 							nodesToWrap,
6358 							undefined,
6359 							createLi,
6360 							range
6361 						));
6362 					}
6363 				}
6364 
6365 				// "If sublist's first member's parent is an HTML element with
6366 				// local name tag name, or if every member of sublist is an ol or
6367 				// ul, continue this loop from the beginning."
6368 				if (isHtmlElement_obsolete(sublist[0].parentNode, tagName) || $_(sublist).every(isOlUl)) {
6369 					continue;
6370 				}
6371 
6372 				// "If sublist's first member's parent is an HTML element with
6373 				// local name other tag name:"
6374 				if (isHtmlElement_obsolete(sublist[0].parentNode, otherTagName)) {
6375 					// "Record the values of sublist, and let values be the
6376 					// result."
6377 					values = recordValues(sublist);
6378 
6379 					// "Split the parent of sublist."
6380 					splitParent(sublist, range);
6381 
6382 					// "Wrap sublist, with sibling criteria returning true for an
6383 					// HTML element with local name tag name and false otherwise,
6384 					// and new parent instructions returning the result of calling
6385 					// createElement(tag name) on the context object."
6386 					wrap(
6387 						sublist,
6388 						makeIsElementPred(tagName),
6389 						makeCreateElement(tagName),
6390 						range
6391 					);
6392 
6393 					// "Restore the values from values."
6394 					restoreValues(values, range);
6395 
6396 					// "Continue this loop from the beginning."
6397 					continue;
6398 				}
6399 
6400 				// "Wrap sublist, with sibling criteria returning true for an HTML
6401 				// element with local name tag name and false otherwise, and new
6402 				// parent instructions being the following:"
6403 				// . . .
6404 				// "Fix disallowed ancestors of the previous step's result."
6405 				fixDisallowedAncestors(wrap(
6406 					sublist,
6407 					makeIsElementPred(tagName),
6408 					makeCreateElementSublist(tagName, sublist, range),
6409 					range
6410 				), range);
6411 			}
6412 		}
6413 	}
6414 
6415 
6416 	//@}
6417 	///// Justifying the selection /////
6418 	//@{
6419 
6420 	function justifySelection(alignment, range) {
6421 
6422 		// "Block-extend the active range, and let new range be the result."
6423 		var newRange = blockExtend(range);
6424 
6425 		// "Let element list be a list of all editable Elements contained in new
6426 		// range that either has an attribute in the HTML namespace whose local
6427 		// name is "align", or has a style attribute that sets "text-align", or is
6428 		// a center."
6429 		var elementList = getAllContainedNodes(newRange, function (node) {
6430 			return node.nodeType == $_.Node.ELEMENT_NODE && isEditable(node)
6431 			// Ignoring namespaces here
6432 				&& (hasAttribute(node, "align") || node.style.textAlign != "" || isNamedHtmlElement(node, 'center'));
6433 		});
6434 
6435 		// "For each element in element list:"
6436 		var i;
6437 		for (i = 0; i < elementList.length; i++) {
6438 			var element = elementList[i];
6439 
6440 			// "If element has an attribute in the HTML namespace whose local name
6441 			// is "align", remove that attribute."
6442 			element.removeAttribute("align");
6443 
6444 			// "Unset the CSS property "text-align" on element, if it's set by a
6445 			// style attribute."
6446 			element.style.textAlign = "";
6447 			if (element.getAttribute("style") == "") {
6448 				element.removeAttribute("style");
6449 			}
6450 
6451 			// "If element is a div or span or center with no attributes, remove
6452 			// it, preserving its descendants."
6453 			if (isHtmlElementInArray(element, ["div", "span", "center"]) && !element.attributes.length) {
6454 				removePreservingDescendants(element, range);
6455 			}
6456 
6457 			// "If element is a center with one or more attributes, set the tag
6458 			// name of element to "div"."
6459 			if (isNamedHtmlElement(element, 'center') && element.attributes.length) {
6460 				setTagName(element, "div", range);
6461 			}
6462 		}
6463 
6464 		// "Block-extend the active range, and let new range be the result."
6465 		newRange = blockExtend(globalRange);
6466 
6467 		// "Let node list be a list of nodes, initially empty."
6468 		var nodeList = [];
6469 
6470 		// "For each node node contained in new range, append node to node list if
6471 6472 		// the last member of node list (if any) is not an ancestor of node; node
6473 		// is editable; node is an allowed child of "div"; and node's alignment
6474 		// value is not alignment."
6475 		nodeList = getContainedNodes(newRange, function (node) {
6476 			return isEditable(node) && isAllowedChild(node, "div") && getAlignmentValue(node) != alignment;
6477 		});
6478 
6479 		function makeIsAlignedDiv(alignment) {
6480 			return function (node) {
6481 				return isNamedHtmlElement(node, 'div') && $_(node.attributes).every(function (attr) {
6482 					return (attr.name == "align" && attr.value.toLowerCase() == alignment) || (attr.name == "style" && getStyleLength(node) == 1 && node.style.textAlign == alignment);
6483 				});
6484 			};
6485 		}
6486 
6487 		function makeCreateAlignedDiv(alignment) {
6488 			return function () {
6489 				var newParent = document.createElement("div");
6490 				newParent.setAttribute("style", "text-align: " + alignment);
6491 				return newParent;
6492 			};
6493 		}
6494 
6495 		// "While node list is not empty:"
6496 		while (nodeList.length) {
6497 			// "Let sublist be a list of nodes, initially empty."
6498 			var sublist = [];
6499 
6500 			// "Remove the first member of node list and append it to sublist."
6501 			sublist.push(nodeList.shift());
6502 
6503 			// "While node list is not empty, and the first member of node list is
6504 			// the nextSibling of the last member of sublist, remove the first
6505 			// member of node list and append it to sublist."
6506 			while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling) {
6507 				sublist.push(nodeList.shift());
6508 			}
6509 
6510 			// "Wrap sublist. Sibling criteria returns true for any div that has
6511 			// one or both of the following two attributes and no other attributes,
6512 			// and false otherwise:"
6513 			//
6514 			//   * "An align attribute whose value is an ASCII case-insensitive
6515 			//     match for alignment.
6516 			//   * "A style attribute which sets exactly one CSS property
6517 			//     (including unrecognized or invalid attributes), which is
6518 			//     "text-align", which is set to alignment.
6519 			//
6520 			// "New parent instructions are to call createElement("div") on the
6521 			// context object, then set its CSS property "text-align" to alignment
6522 			// and return the result."
6523 6524 			wrap(
6525 				sublist,
6526 				makeIsAlignedDiv(alignment),
6527 				makeCreateAlignedDiv(alignment),
6528 				range
6529 			);
6530 		}
6531 	}
6532 
6533 	//@}
6534 	///// Move the given collapsed range over adjacent zero-width whitespace characters.
6535 	///// The range is
6536 	//@{
6537 	/**
6538 	 * Move the given collapsed range over adjacent zero-width whitespace characters.
6539 	 * If the range is not collapsed or is not contained in a text node, it is not modified
6540 	 * @param range range to modify
6541 	 * @param forward {Boolean} true to move forward, false to move backward
6542 6543 	 */
6544 	function moveOverZWSP(range, forward) {
6545 		var offset;
6546 		if (!range.collapsed) {
6547 			return;
6548 		}
6549 
6550 		offset = range.startOffset;
6551 
6552 		if (forward) {
6553 			// check whether the range starts in a text node
6554 			if (range.startContainer && range.startContainer.nodeType === $_.Node.TEXT_NODE) {
6555 				// move forward (i.e. increase offset) as long as we stay in the text node and have zwsp characters to the right
6556 				while (offset < range.startContainer.data.length && range.startContainer.data.charAt(offset) === '\u200b') {
6557 					offset++;
6558 				}
6559 			}
6560 		} else {
6561 			// check whether the range starts in a text node
6562 			if (range.startContainer && range.startContainer.nodeType === $_.Node.TEXT_NODE) {
6563 				// move backward (i.e. decrease offset) as long as we stay in the text node and have zwsp characters to the left
6564 				while (offset > 0 && range.startContainer.data.charAt(offset - 1) === '\u200b') {
6565 					offset--;
6566 				}
6567 			}
6568 		}
6569 
6570 		// if the offset was changed, set it back to the collapsed range
6571 		if (offset !== range.startOffset) {
6572 			range.setStart(range.startContainer, offset);
6573 			range.setEnd(range.startContainer, offset);
6574 		}
6575 	}
6576 
6577 	/**
6578 	 * implementation of the delete command
6579 	 * will attempt to delete contents within range if non-collapsed
6580 	 * or delete the character left of the cursor position if range
6581 	 * is collapsed. Is used to define the behaviour of the backspace
6582 	 * button.
6583 	 *
6584 	 * @param      value   is just there for compatibility with the commands api. parameter is ignored.
6585 	 * @param      range   the range to execute the delete command for
6586 	 * @return     void
6587 	 */
6588 	commands["delete"] = {
6589 		action: function (value, range) {
6590 			var i;
6591 
6592 			// special behaviour for skipping zero-width whitespaces in IE7
6593 			if (jQuery.browser.msie && jQuery.browser.version <= 7) {
6594 				moveOverZWSP(range, false);
6595 			}
6596 
6597 			// "If the active range is not collapsed, delete the contents of the
6598 			// active range and abort these steps."
6599 			if (!range.collapsed) {
6600 				deleteContents(range);
6601 				return;
6602 			}
6603 
6604 			// "Canonicalize whitespace at (active range's start node, active
6605 			// range's start offset)."
6606 			canonicalizeWhitespace(range.startContainer, range.startOffset);
6607 
6608 			// "Let node and offset be the active range's start node and offset."
6609 			var node = range.startContainer;
6610 			var offset = range.startOffset;
6611 			var isBr = false;
6612 			var isHr = false;
6613 
6614 			// "Repeat the following steps:"
6615 			while (true) {
6616 				// we need to reset isBr and isHr on every interation of the loop
6617 				if (offset > 0) {
6618 					isBr = isNamedHtmlElement(node.childNodes[offset - 1], "br") || false;
6619 					isHr = isNamedHtmlElement(node.childNodes[offset - 1], "hr") || false;
6620 				}
6621 				// "If offset is zero and node's previousSibling is an editable
6622 				// invisible node, remove node's previousSibling from its parent."
6623 				if (offset == 0 && isEditable(node.previousSibling) && isInvisible(node.previousSibling)) {
6624 					node.parentNode.removeChild(node.previousSibling);
6625 					continue;
6626 				}
6627 				// "Otherwise, if node has a child with index offset − 1 and that
6628 				// child is an editable invisible node, remove that child from
6629 				// node, then subtract one from offset."
6630 				if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isEditable(node.childNodes[offset - 1]) && (isInvisible(node.childNodes[offset - 1]) || isBr || isHr)) {
6631 					node.removeChild(node.childNodes[offset - 1]);
6632 					offset--;
6633 					if (isBr || isHr) {
6634 						range.setStart(node, offset);
6635 						range.setEnd(node, offset);
6636 						return;
6637 					}
6638 					continue;
6639 
6640 				}
6641 				// "Otherwise, if offset is zero and node is an inline node, or if
6642 				// node is an invisible node, set offset to the index of node, then
6643 				// set node to its parent."
6644 				if ((offset == 0 && isInlineNode(node)) || isInvisible(node)) {
6645 					offset = Dom.getIndexInParent(node);
6646 					node = node.parentNode;
6647 					continue;
6648 				}
6649 				// "Otherwise, if node has a child with index offset − 1 and that
6650 				// child is an editable a, remove that child from node, preserving
6651 				// its descendants. Then abort these steps."
6652 				if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isEditable(node.childNodes[offset - 1]) && isNamedHtmlElement(node.childNodes[offset - 1], "a")) {
6653 					removePreservingDescendants(node.childNodes[offset - 1], range);
6654 					return;
6655 
6656 				}
6657 				// "Otherwise, if node has a child with index offset − 1 and that
6658 				// child is not a block node or a br or an img, set node to that
6659 				// child, then set offset to the length of node."
6660 				if (0 <= offset - 1 && offset - 1 < node.childNodes.length && !isBlockNode(node.childNodes[offset - 1]) && !isHtmlElementInArray(node.childNodes[offset - 1], ["br", "img"])) {
6661 					node = node.childNodes[offset - 1];
6662 					offset = getNodeLength(node);
6663 					continue;
6664 				}
6665 				// "Otherwise, break from this loop."
6666 				// brk is a quick and dirty jslint workaround since I don't want to rewrite this loop
6667 				var brk = true;
6668 				if (brk) {
6669 					break;
6670 				}
6671 			}
6672 
6673 			// if the previous node is an aloha-table we want to delete it
6674 			var delBlock = getBlockAtPreviousPosition(node, offset);
6675 			if (delBlock) {
6676 				delBlock.parentNode.removeChild(delBlock);
6677 				return;
6678 			}
6679 
6680 			// "If node is a Text node and offset is not zero, call collapse(node,
6681 			// offset) on the Selection. Then delete the contents of the range with
6682 			// start (node, offset − 1) and end (node, offset) and abort these
6683 			// steps."
6684 			if (node.nodeType == $_.Node.TEXT_NODE && offset != 0) {
6685 				range.setStart(node, offset - 1);
6686 				range.setEnd(node, offset - 1);
6687 				deleteContents(node, offset - 1, node, offset);
6688 				return;
6689 			}
6690 
6691 			// @iebug
6692 			// when inserting a special char via the plugin
6693 			// there where problems deleting them again with backspace after insertation
6694 			// see https://github.com/alohaeditor/Aloha-Editor/issues/517
6695 			if (node.nodeType == $_.Node.TEXT_NODE && offset == 0 && jQuery.browser.msie) {
6696 				offset = 1;
6697 				range.setStart(node, offset);
6698 				range.setEnd(node, offset);
6699 				range.startOffset = 0;
6700 				deleteContents(range);
6701 				return;
6702 			}
6703 
6704 			// "If node is an inline node, abort these steps."
6705 			if (isInlineNode(node)) {
6706 				return;
6707 			}
6708 
6709 			// "If node has a child with index offset − 1 and that child is a br or
6710 			// hr or img, call collapse(node, offset) on the Selection. Then delete
6711 			// the contents of the range with start (node, offset − 1) and end
6712 			// (node, offset) and abort these steps."
6713 			if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isHtmlElementInArray(node.childNodes[offset - 1], ["br", "hr", "img"])) {
6714 				range.setStart(node, offset);
6715 				range.setEnd(node, offset);
6716 				deleteContents(range);
6717 				return;
6718 			}
6719 
6720 			// "If node is an li or dt or dd and is the first child of its parent,
6721 			// and offset is zero:"
6722 			if (isHtmlElementInArray(node, ["li", "dt", "dd"]) && node == node.parentNode.firstChild && offset == 0) {
6723 				// "Let items be a list of all lis that are ancestors of node."
6724 				//
6725 				// Remember, must be in tree order.
6726 				var items = [];
6727 				var ancestor;
6728 				for (ancestor = node.parentNode; ancestor; ancestor = ancestor.parentNode) {
6729 					if (isNamedHtmlElement(ancestor, 'li')) {
6730 						items.unshift(ancestor);
6731 					}
6732 				}
6733 
6734 				// "Normalize sublists of each item in items."
6735 				for (i = 0; i < items.length; i++) {
6736 					normalizeSublists(items[i], range);
6737 				}
6738 
6739 				// "Record the values of the one-node list consisting of node, and
6740 				// let values be the result."
6741 				var values = recordValues([node]);
6742 
6743 				// "Split the parent of the one-node list consisting of node."
6744 				splitParent([node], range);
6745 
6746 				// "Restore the values from values."
6747 				restoreValues(values, range);
6748 
6749 				// "If node is a dd or dt, and it is not an allowed child of any of
6750 				// its ancestors in the same editing host, set the tag name of node
6751 				// to the default single-line container name and let node be the
6752 				// result."
6753 				if (isHtmlElementInArray(node, ["dd", "dt"]) && $_(getAncestors(node)).every(function (ancestor) { return !inSameEditingHost(node, ancestor) || !isAllowedChild(node, ancestor); })) {
6754 					node = setTagName(node, defaultSingleLineContainerName, range);
6755 				}
6756 6757 
				// "Fix disallowed ancestors of node."
6758 				fixDisallowedAncestors(node, range);
6759 
6760 				// fix the lists to be html5 conformant
6761 				for (i = 0; i < items.length; i++) {
6762 					unNormalizeSublists(items[i].parentNode, range);
6763 				}
6764 
6765 				// "Abort these steps."
6766 				return;
6767 			}
6768 6769 
			// "Let start node equal node and let start offset equal offset."
6770 			var startNode = node;
6771 			var startOffset = offset;
6772 
6773 			// "Repeat the following steps:"
6774 			while (true) {
6775 				// "If start offset is zero, set start offset to the index of start
6776 				// node and then set start node to its parent."
6777 				if (startOffset == 0) {
6778 					startOffset = Dom.getIndexInParent(startNode);
6779 					startNode = startNode.parentNode;
6780 
6781 					// "Otherwise, if start node has an editable invisible child with
6782 					// index start offset minus one, remove it from start node and
6783 					// subtract one from start offset."
6784 				} else if (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length && isEditable(startNode.childNodes[startOffset - 1]) && isInvisible(startNode.childNodes[startOffset - 1])) {
6785 					startNode.removeChild(startNode.childNodes[startOffset - 1]);
6786 					startOffset--;
6787 
6788 					// "Otherwise, break from this loop."
6789 				} else {
6790 					break;
6791 				}
6792 			}
6793 
6794 			// "If offset is zero, and node has an editable ancestor container in
6795 			// the same editing host that's an indentation element:"
6796 			if (offset == 0 && $_(getAncestors(node).concat(node)).filter(function (ancestor) { return isEditable(ancestor) && inSameEditingHost(ancestor, node) && isIndentationElement(ancestor); }).length) {
6797 				// "Block-extend the range whose start and end are both (node, 0),
6798 				// and let new range be the result."
6799 				var newRange = Aloha.createRange();
6800 				newRange.setStart(node, 0);
6801 				newRange.setEnd(node, 0);
6802 				newRange = blockExtend(newRange);
6803 
6804 				// "Let node list be a list of nodes, initially empty."
6805 				//
6806 				// "For each node current node contained in new range, append
6807 				// current node to node list if the last member of node list (if
6808 				// any) is not an ancestor of current node, and current node is
6809 				// editable but has no editable descendants."
6810 				var nodeList = getContainedNodes(newRange, function (currentNode) {
6811 					return isEditable(currentNode) && !hasEditableDescendants(currentNode);
6812 				});
6813 
6814 				// "Outdent each node in node list."
6815 				for (i = 0; i < nodeList.length; i++) {
6816 					outdentNode(nodeList[i], range);
6817 				}
6818 
6819 				// "Abort these steps."
6820 				return;
6821 			}
6822 
6823 			// "If the child of start node with index start offset is a table,
6824 			// abort these steps."
6825 			if (isNamedHtmlElement(startNode.childNodes[startOffset], "table")) {
6826 				return;
6827 			}
6828 
6829 			// "If start node has a child with index start offset − 1, and that
6830 			// child is a table:"
6831 			if (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length && isNamedHtmlElement(startNode.childNodes[startOffset - 1], "table")) {
6832 				// "Call collapse(start node, start offset − 1) on the context
6833 				// object's Selection."
6834 				range.setStart(startNode, startOffset - 1);
6835 
6836 				// "Call extend(start node, start offset) on the context object's
6837 				// Selection."
6838 				range.setEnd(startNode, startOffset);
6839 
6840 				// "Abort these steps."
6841 				return;
6842 			}
6843 
6844 			// "If offset is zero; and either the child of start node with index
6845 			// start offset minus one is an hr, or the child is a br whose
6846 			// previousSibling is either a br or not an inline node:"
6847 			if (offset == 0
6848 				    && (isNamedHtmlElement(startNode.childNodes[startOffset - 1], "hr")
6849 						|| (isNamedHtmlElement(startNode.childNodes[startOffset - 1], "br")
6850 							&& (isNamedHtmlElement(startNode.childNodes[startOffset - 1].previousSibling, "br")
6851 								|| !isInlineNode(startNode.childNodes[startOffset - 1].previousSibling))))) {
6852 				// "Call collapse(node, offset) on the Selection."
6853 				range.setStart(node, offset);
6854 				range.setEnd(node, offset);
6855 
6856 				// "Delete the contents of the range with start (start node, start
6857 				// offset − 1) and end (start node, start offset)."
6858 				deleteContents(startNode, startOffset - 1, startNode, startOffset);
6859 
6860 				// "Abort these steps."
6861 				return;
6862 			}
6863 
6864 			// "If the child of start node with index start offset is an li or dt
6865 			// or dd, and that child's firstChild is an inline node, and start
6866 			// offset is not zero:"
6867 			if (isHtmlElementInArray(startNode.childNodes[startOffset], ["li", "dt", "dd"]) && isInlineNode(startNode.childNodes[startOffset].firstChild) && startOffset != 0) {
6868 				// "Let previous item be the child of start node with index start
6869 				// offset minus one."
6870 				var previousItem = startNode.childNodes[startOffset - 1];
6871 
6872 				// "If previous item's lastChild is an inline node other than a br,
6873 				// call createElement("br") on the context object and append the
6874 				// result as the last child of previous item."
6875 				if (isInlineNode(previousItem.lastChild) && !isNamedHtmlElement(previousItem.lastChild, "br")) {
6876 					previousItem.appendChild(document.createElement("br"));
6877 				}
6878 
6879 				// "If previous item's lastChild is an inline node, call
6880 				// createElement("br") on the context object and append the result
6881 				// as the last child of previous item."
6882 				if (isInlineNode(previousItem.lastChild)) {
6883 					previousItem.appendChild(document.createElement("br"));
6884 				}
6885 			}
6886 
6887 			// "If the child of start node with index start offset is an li or dt
6888 			// or dd, and its previousSibling is also an li or dt or dd, set start
6889 			// node to its child with index start offset − 1, then set start offset
6890 			// to start node's length, then set node to start node's nextSibling,
6891 			// then set offset to 0."
6892 			if (isHtmlElementInArray(startNode.childNodes[startOffset], ["li", "dt", "dd"]) && isHtmlElementInArray(startNode.childNodes[startOffset - 1], ["li", "dt", "dd"])) {
6893 				startNode = startNode.childNodes[startOffset - 1];
6894 				startOffset = getNodeLength(startNode);
6895 				node = startNode.nextSibling;
6896 				offset = 0;
6897 
6898 				// "Otherwise, while start node has a child with index start offset
6899 				// minus one:"
6900 			} else {
6901 				while (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length) {
6902 					// "If start node's child with index start offset minus one is
6903 					// editable and invisible, remove it from start node, then
6904 					// subtract one from start offset."
6905 					if (isEditable(startNode.childNodes[startOffset - 1]) && isInvisible(startNode.childNodes[startOffset - 1])) {
6906 						startNode.removeChild(startNode.childNodes[startOffset - 1]);
6907 						startOffset--;
6908 
6909 						// "Otherwise, set start node to its child with index start
6910 						// offset minus one, then set start offset to the length of
6911 						// start node."
6912 					} else {
6913 						startNode = startNode.childNodes[startOffset - 1];
6914 						startOffset = getNodeLength(startNode);
6915 					}
6916 				}
6917 			}
6918 
6919 			// "Delete the contents of the range with start (start node, start
6920 			// offset) and end (node, offset)."
6921 			var delRange = Aloha.createRange();
6922 			delRange.setStart(startNode, startOffset);
6923 			delRange.setEnd(node, offset);
6924 			deleteContents(delRange);
6925 
6926 			if (!isAncestorContainer(document.body, range.startContainer)) {
6927 				if (delRange.startContainer.hasChildNodes()
6928 						|| delRange.startContainer.nodeType == $_.Node.TEXT_NODE
6929 							|| isEditingHost(delRange.startContainer)) {
6930 					range.setStart(delRange.startContainer, delRange.startOffset);
6931 					range.setEnd(delRange.startContainer, delRange.startOffset);
6932 				} else {
6933 					range.setStart(delRange.startContainer.parentNode, Dom.getIndexInParent(delRange.startContainer));
6934 					range.setEnd(delRange.startContainer.parentNode, Dom.getIndexInParent(delRange.startContainer));
6935 				}
6936 			}
6937 		}
6938 	};
6939 
6940 	//@}
6941 	///// The formatBlock command /////
6942 	//@{
6943 	// "A formattable block name is "address", "dd", "div", "dt", "h1", "h2", "h3",
6944 	// "h4", "h5", "h6", "p", or "pre"."
6945 	var formattableBlockNames = ["address", "dd", "div", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "p", "pre"];
6946 
6947 	commands.formatblock = {
6948 		action: function (value) {
6949 			var i;
6950 
6951 			// "If value begins with a "<" character and ends with a ">" character,
6952 			// remove the first and last characters from it."
6953 			if (/^<.*>$/.test(value)) {
6954 				value = value.slice(1, -1);
6955 			}
6956 
6957 			// "Let value be converted to ASCII lowercase."
6958 			value = value.toLowerCase();
6959 
6960 			// "If value is not a formattable block name, abort these steps and do
6961 			// nothing."
6962 			if ($_(formattableBlockNames).indexOf(value) == -1) {
6963 				return;
6964 			}
6965 
6966 			// "Block-extend the active range, and let new range be the result."
6967 			var newRange = blockExtend(getActiveRange());
6968 
6969 			// "Let node list be an empty list of nodes."
6970 			//
6971 			// "For each node node contained in new range, append node to node list
6972 			// if it is editable, the last member of original node list (if any) is
6973 			// not an ancestor of node, node is either a non-list single-line
6974 			// container or an allowed child of "p" or a dd or dt, and node is not
6975 			// the ancestor of a prohibited paragraph child."
6976 			var nodeList = getContainedNodes(newRange, function (node) {
6977 				return isEditable(node) && (isNonListSingleLineContainer(node) || isAllowedChild(node, "p") || isHtmlElementInArray(node, ["dd", "dt"])) && !$_(getDescendants(node)).some(isProhibitedParagraphChild);
6978 			});
6979 
6980 			// "Record the values of node list, and let values be the result."
6981 			var values = recordValues(nodeList);
6982 
6983 			function makeIsEditableElementInSameEditingHostDoesNotContainProhibitedParagraphChildren(node) {
6984 				return function (ancestor) {
6985 					return (isEditable(ancestor)
6986 							&& inSameEditingHost(ancestor, node)
6987 							&& isHtmlElement_obsolete(ancestor, formattableBlockNames)
6988 							&& !$_(getDescendants(ancestor)).some(isProhibitedParagraphChild));
6989 				};
6990 			}
6991 
6992 			function makeIsElementWithoutAttributes(value) {
6993 				return function (node) {
6994 					return isHtmlElement_obsolete(node, value) && !node.attributes.length;
6995 				};
6996 			}
6997 
6998 			function returnFalse() {
6999 				return false;
7000 			}
7001 
7002 			function makeCreateElement(value) {
7003 				return function () {
7004 					return document.createElement(value);
7005 				};
7006 			}
7007 
7008 			// "For each node in node list, while node is the descendant of an
7009 			// editable HTML element in the same editing host, whose local name is
7010 			// a formattable block name, and which is not the ancestor of a
7011 			// prohibited paragraph child, split the parent of the one-node list
7012 			// consisting of node."
7013 			for (i = 0; i < nodeList.length; i++) {
7014 				var node = nodeList[i];
7015 				while ($_(getAncestors(node)).some(makeIsEditableElementInSameEditingHostDoesNotContainProhibitedParagraphChildren(node))) {
7016 					splitParent([node], newRange);
7017 				}
7018 			}
7019 
7020 			// "Restore the values from values."
7021 			restoreValues(values, newRange);
7022 
7023 			// "While node list is not empty:"
7024 			while (nodeList.length) {
7025 				var sublist;
7026 
7027 				// "If the first member of node list is a single-line
7028 				// container:"
7029 				if (isSingleLineContainer(nodeList[0])) {
7030 					// "Let sublist be the children of the first member of node
7031 					// list."
7032 					sublist = [].slice.call(toArray(nodeList[0].childNodes));
7033 
7034 					// "Record the values of sublist, and let values be the
7035 					// result."
7036 					values = recordValues(sublist);
7037 
7038 					// "Remove the first member of node list from its parent,
7039 					// preserving its descendants."
7040 					removePreservingDescendants(nodeList[0], newRange);
7041 
7042 					// "Restore the values from values."
7043 					restoreValues(values, newRange);
7044 
7045 					// "Remove the first member from node list."
7046 					nodeList.shift();
7047 
7048 					// "Otherwise:"
7049 				} else {
7050 					// "Let sublist be an empty list of nodes."
7051 					sublist = [];
7052 
7053 					// "Remove the first member of node list and append it to
7054 					// sublist."
7055 					sublist.push(nodeList.shift());
7056 
7057 					// "While node list is not empty, and the first member of
7058 					// node list is the nextSibling of the last member of
7059 					// sublist, and the first member of node list is not a
7060 					// single-line container, and the last member of sublist is
7061 					// not a br, remove the first member of node list and
7062 					// append it to sublist."
7063 					while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isSingleLineContainer(nodeList[0]) && !isNamedHtmlElement(sublist[sublist.length - 1], "BR")) {
7064 						sublist.push(nodeList.shift());
7065 					}
7066 				}
7067 
7068 				// "Wrap sublist. If value is "div" or "p", sibling criteria
7069 				// returns false; otherwise it returns true for an HTML element
7070 				// with local name value and no attributes, and false otherwise.
7071 				// New parent instructions return the result of running
7072 				// createElement(value) on the context object. Then fix disallowed
7073 				// ancestors of the result."
7074 				fixDisallowedAncestors(wrap(
7075 					sublist,
7076 					jQuery.inArray(value, ["div", "p"]) == -1 ? makeIsElementWithoutAttributes(value) : returnFalse,
7077 					makeCreateElement(value),
7078 					newRange
7079 				), newRange);
7080 			}
7081 		},
7082 		indeterm: function () {
7083 			// "Block-extend the active range, and let new range be the result."
7084 			var newRange = blockExtend(getActiveRange());
7085 
7086 			// "Let node list be all visible editable nodes that are contained in
7087 			// new range and have no children."
7088 			var nodeList = getAllContainedNodes(newRange, function (node) {
7089 				return isVisible(node) && isEditable(node) && !node.hasChildNodes();
7090 			});
7091 
7092 			// "If node list is empty, return false."
7093 			if (!nodeList.length) {
7094 				return false;
7095 			}
7096 
7097 			// "Let type be null."
7098 			var type = null;
7099 
7100 			// "For each node in node list:"
7101 			var i;
7102 			for (i = 0; i < nodeList.length; i++) {
7103 				var node = nodeList[i];
7104 
7105 				// "While node's parent is editable and in the same editing host as
7106 				// node, and node is not an HTML element whose local name is a
7107 				// formattable block name, set node to its parent."
7108 				while (isEditable(node.parentNode) && inSameEditingHost(node, node.parentNode) && !isHtmlElement_obsolete(node, formattableBlockNames)) {
7109 					node = node.parentNode;
7110 				}
7111 
7112 				// "Let current type be the empty string."
7113 				var currentType = "";
7114 
7115 				// "If node is an editable HTML element whose local name is a
7116 				// formattable block name, and node is not the ancestor of a
7117 				// prohibited paragraph child, set current type to node's local
7118 				// name."
7119 				if (isEditable(node) && isHtmlElement_obsolete(node, formattableBlockNames) && !$_(getDescendants(node)).some(isProhibitedParagraphChild)) {
7120 					currentType = node.tagName;
7121 				}
7122 
7123 				// "If type is null, set type to current type."
7124 				if (type === null) {
7125 					type = currentType;
7126 
7127 					// "Otherwise, if type does not equal current type, return true."
7128 				} else if (type != currentType) {
7129 					return true;
7130 				}
7131 			}
7132 
7133 			// "Return false."
7134 			return false;
7135 		},
7136 		value: function () {
7137 			// "Block-extend the active range, and let new range be the result."
7138 			var newRange = blockExtend(getActiveRange());
7139 
7140 			// "Let node be the first visible editable node that is contained in
7141 			// new range and has no children. If there is no such node, return the
7142 			// empty string."
7143 			var nodes = getAllContainedNodes(newRange, function (node) {
7144 				return isVisible(node) && isEditable(node) && !node.hasChildNodes();
7145 			});
7146 			if (!nodes.length) {
7147 				return "";
7148 			}
7149 			var node = nodes[0];
7150 
7151 			// "While node's parent is editable and in the same editing host as
7152 			// node, and node is not an HTML element whose local name is a
7153 			// formattable block name, set node to its parent."
7154 			while (isEditable(node.parentNode) && inSameEditingHost(node, node.parentNode) && !isHtmlElement_obsolete(node, formattableBlockNames)) {
7155 				node = node.parentNode;
7156 			}
7157 
7158 			// "If node is an editable HTML element whose local name is a
7159 			// formattable block name, and node is not the ancestor of a prohibited
7160 			// paragraph child, return node's local name, converted to ASCII
7161 			// lowercase."
7162 			if (isEditable(node) && isHtmlElement_obsolete(node, formattableBlockNames) && !$_(getDescendants(node)).some(isProhibitedParagraphChild)) {
7163 				return node.tagName.toLowerCase();
7164 			}
7165 
7166 			// "Return the empty string."
7167 			return "";
7168 		}
7169 	};
7170 
7171 	//@}
7172 	///// The forwardDelete command /////
7173 	//@{
7174 	commands.forwarddelete = {
7175 		action: function (value, range) {
7176 			// special behaviour for skipping zero-width whitespaces in IE7
7177 			if (jQuery.browser.msie && jQuery.browser.version <= 7) {
7178 				moveOverZWSP(range, true);
7179 			}
7180 
7181 			// "If the active range is not collapsed, delete the contents of the
7182 			// active range and abort these steps."
7183 			if (!range.collapsed) {
7184 				deleteContents(range);
7185 				return;
7186 			}
7187 
7188 			// "Canonicalize whitespace at (active range's start node, active
7189 			// range's start offset)."
7190 			canonicalizeWhitespace(range.startContainer, range.startOffset);
7191 
7192 			// "Let node and offset be the active range's start node and offset."
7193 			var node = range.startContainer;
7194 			var offset = range.startOffset;
7195 			var isBr = false;
7196 			var isHr = false;
7197 
7198 			// "Repeat the following steps:"
7199 			while (true) {
7200 				// check whether the next element is a br or hr
7201 				// Commented out for unknown reason.
7202 				//if (offset < node.childNodes.length) {
7203 				//				isBr = isHtmlElement_obsolete(node.childNodes[offset], "br") || false;
7204 				//				isHr = isHtmlElement_obsolete(node.childNodes[offset], "hr") || false;
7205 				//}
7206 
7207 				// "If offset is the length of node and node's nextSibling is an
7208 				// editable invisible node, remove node's nextSibling from its
7209 				// parent."
7210 				if (offset == getNodeLength(node) && isEditable(node.nextSibling) && isInvisible(node.nextSibling)) {
7211 					node.parentNode.removeChild(node.nextSibling);
7212 
7213 					// "Otherwise, if node has a child with index offset and that child
7214 					// is an editable invisible node, remove that child from node."
7215 				} else if (offset < node.childNodes.length && isEditable(node.childNodes[offset]) && (isInvisible(node.childNodes[offset]) || isBr || isHr)) {
7216 					node.removeChild(node.childNodes[offset]);
7217 					if (isBr || isHr) {
7218 						ensureContainerEditable(node);
7219 						range.setStart(node, offset);
7220 						range.setEnd(node, offset);
7221 						return;
7222 					}
7223 
7224 					// "Otherwise, if node has a child with index offset and that child
7225 					// is a collapsed block prop, add one to offset."
7226 				} else if (offset < node.childNodes.length && isCollapsedBlockProp(node.childNodes[offset])) {
7227 					offset++;
7228 
7229 					// "Otherwise, if offset is the length of node and node is an
7230 					// inline node, or if node is invisible, set offset to one plus the
7231 					// index of node, then set node to its parent."
7232 				} else if ((offset == getNodeLength(node) && isInlineNode(node)) || isInvisible(node)) {
7233 					offset = 1 + Dom.getIndexInParent(node);
7234 					node = node.parentNode;
7235 
7236 					// "Otherwise, if node has a child with index offset and that child
7237 					// is not a block node or a br or an img, set node to that child,
7238 					// then set offset to zero."
7239 				} else if (offset < node.childNodes.length && !isBlockNode(node.childNodes[offset]) && !isHtmlElementInArray(node.childNodes[offset], ["br", "img"])) {
7240 					node = node.childNodes[offset];
7241 					offset = 0;
7242 
7243 					// "Otherwise, break from this loop."
7244 				} else {
7245 					break;
7246 				}
7247 			}
7248 
7249 			// collapse whitespace in the node, if it is a text node
7250 			canonicalizeWhitespace(range.startContainer, range.startOffset);
7251 
7252 			// if the next node is an aloha-table we want to delete it
7253 			var delBlock = getBlockAtNextPosition(node, offset);
7254 			if (delBlock) {
7255 				delBlock.parentNode.removeChild(delBlock);
7256 				return;
7257 			}
7258 
7259 			var endOffset;
7260 			// "If node is a Text node and offset is not node's length:"
7261 			if (node.nodeType == $_.Node.TEXT_NODE && offset != getNodeLength(node)) {
7262 				// "Call collapse(node, offset) on the Selection."
7263 				range.setStart(node, offset);
7264 				range.setEnd(node, offset);
7265 
7266 				// "Let end offset be offset plus one."
7267 				endOffset = offset + 1;
7268 
7269 				// "While end offset is not node's length and the end offsetth
7270 				// element of node's data has general category M when interpreted
7271 				// as a Unicode code point, add one to end offset."
7272 				//
7273 				// TODO: Not even going to try handling anything beyond the most
7274 				// basic combining marks, since I couldn't find a good list.  I
7275 				// special-case a few Hebrew diacritics too to test basic coverage
7276 				// of non-Latin stuff.
7277 				while (endOffset != node.length && /^[\u0300-\u036f\u0591-\u05bd\u05c1\u05c2]$/.test(node.data[endOffset])) {
7278 					endOffset++;
7279 				}
7280 
7281 				// "Delete the contents of the range with start (node, offset) and
7282 				// end (node, end offset)."
7283 				deleteContents(node, offset, node, endOffset);
7284 
7285 				// "Abort these steps."
7286 				return;
7287 			}
7288 
7289 			// "If node is an inline node, abort these steps."
7290 			if (isInlineNode(node)) {
7291 				return;
7292 			}
7293 
7294 			// "If node has a child with index offset and that child is a br or hr
7295 			// or img, call collapse(node, offset) on the Selection. Then delete
7296 			// the contents of the range with start (node, offset) and end (node,
7297 			// offset + 1) and abort these steps."
7298 			if (offset < node.childNodes.length && isHtmlElementInArray(node.childNodes[offset], ["br", "hr", "img"])) {
7299 				range.setStart(node, offset);
7300 				range.setEnd(node, offset);
7301 				deleteContents(node, offset, node, offset + 1);
7302 				return;
7303 			}
7304 
7305 			// "Let end node equal node and let end offset equal offset."
7306 			var endNode = node;
7307 			endOffset = offset;
7308 
7309 			// "Repeat the following steps:"
7310 			while (true) {
7311 				// "If end offset is the length of end node, set end offset to one
7312 				// plus the index of end node and then set end node to its parent."
7313 				if (endOffset == getNodeLength(endNode)) {
7314 					endOffset = 1 + Dom.getIndexInParent(endNode);
7315 					endNode = endNode.parentNode;
7316 
7317 					// "Otherwise, if end node has a an editable invisible child with
7318 					// index end offset, remove it from end node."
7319 				} else if (endOffset < endNode.childNodes.length && isEditable(endNode.childNodes[endOffset]) && isInvisible(endNode.childNodes[endOffset])) {
7320 					endNode.removeChild(endNode.childNodes[endOffset]);
7321 
7322 					// "Otherwise, break from this loop."
7323 				} else {
7324 					break;
7325 				}
7326 			}
7327 
7328 			// "If the child of end node with index end offset minus one is a
7329 			// table, abort these steps."
7330 			if (isNamedHtmlElement(endNode.childNodes[endOffset - 1], "table")) {
7331 				return;
7332 			}
7333 
7334 			// "If the child of end node with index end offset is a table:"
7335 			if (isNamedHtmlElement(endNode.childNodes[endOffset], "table")) {
7336 				// "Call collapse(end node, end offset) on the context object's
7337 				// Selection."
7338 				range.setStart(endNode, endOffset);
7339 
7340 				// "Call extend(end node, end offset + 1) on the context object's
7341 				// Selection."
7342 				range.setEnd(endNode, endOffset + 1);
7343 
7344 				// "Abort these steps."
7345 				return;
7346 			}
7347 
7348 			// "If offset is the length of node, and the child of end node with
7349 			// index end offset is an hr or br:"
7350 			if (offset == getNodeLength(node) && isHtmlElementInArray(endNode.childNodes[endOffset], ["br", "hr"])) {
7351 				// "Call collapse(node, offset) on the Selection."
7352 				range.setStart(node, offset);
7353 				range.setEnd(node, offset);
7354 
7355 				// "Delete the contents of the range with end (end node, end
7356 				// offset) and end (end node, end offset + 1)."
7357 				deleteContents(endNode, endOffset, endNode, endOffset + 1);
7358 
7359 				// "Abort these steps."
7360 				return;
7361 			}
7362 
7363 			// "While end node has a child with index end offset:"
7364 			while (endOffset < endNode.childNodes.length) {
7365 				// "If end node's child with index end offset is editable and
7366 				// invisible, remove it from end node."
7367 				if (isEditable(endNode.childNodes[endOffset]) && isInvisible(endNode.childNodes[endOffset])) {
7368 					endNode.removeChild(endNode.childNodes[endOffset]);
7369 
7370 					// "Otherwise, set end node to its child with index end offset and
7371 					// set end offset to zero."
7372 				} else {
7373 					endNode = endNode.childNodes[endOffset];
7374 					endOffset = 0;
7375 				}
7376 			}
7377 
7378 			// "Delete the contents of the range with start (node, offset) and end
7379 			// (end node, end offset)."
7380 			var newRange = deleteContents(node, offset, endNode, endOffset);
7381 			range.setStart(newRange.startContainer, newRange.startOffset);
7382 			range.setEnd(newRange.endContainer, newRange.endOffset);
7383 		}
7384 	};
7385 
7386 	//@}
7387 	///// The indent command /////
7388 	//@{
7389 	commands.indent = {
7390 		action: function () {
7391 			// "Let items be a list of all lis that are ancestor containers of the
7392 			// active range's start and/or end node."
7393 			//
7394 			// Has to be in tree order, remember!
7395 			var items = [];
7396 			var node;
7397 			for (node = getActiveRange().endContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) {
7398 				if (isNamedHtmlElement(node, "LI")) {
7399 					items.unshift(node);
7400 				}
7401 			}
7402 			for (node = getActiveRange().startContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) {
7403 				if (isNamedHtmlElement(node, "LI")) {
7404 					items.unshift(node);
7405 				}
7406 			}
7407 			for (node = getActiveRange().commonAncestorContainer; node; node = node.parentNode) {
7408 				if (isNamedHtmlElement(node, "LI")) {
7409 					items.unshift(node);
7410 				}
7411 			}
7412 
7413 			// "For each item in items, normalize sublists of item."
7414 			var i;
7415 			for (i = 0; i < items.length; i++) {
7416 				normalizeSublists(items[i], getActiveRange());
7417 			}
7418 
7419 			// "Block-extend the active range, and let new range be the result."
7420 			var newRange = blockExtend(getActiveRange());
7421 
7422 			// "Let node list be a list of nodes, initially empty."
7423 			var nodeList = [];
7424 
7425 			// "For each node node contained in new range, if node is editable and
7426 			// is an allowed child of "div" or "ol" and if the last member of node
7427 			// list (if any) is not an ancestor of node, append node to node list."
7428 			nodeList = getContainedNodes(newRange, function (node) {
7429 				return isEditable(node) && (isAllowedChild(node, "div") || isAllowedChild(node, "ol"));
7430 			});
7431 
7432 			// "If the first member of node list is an li whose parent is an ol or
7433 			// ul, and its previousSibling is an li as well, normalize sublists of
7434 			// its previousSibling."
7435 			if (nodeList.length && isNamedHtmlElement(nodeList[0], "LI") && isHtmlElementInArray(nodeList[0].parentNode, ["OL", "UL"]) && isNamedHtmlElement(nodeList[0].previousSibling, "LI")) {
7436 				normalizeSublists(nodeList[0].previousSibling, newRange);
7437 			}
7438 
7439 			// "While node list is not empty:"
7440 			while (nodeList.length) {
7441 				// "Let sublist be a list of nodes, initially empty."
7442 				var sublist = [];
7443 
7444 				// "Remove the first member of node list and append it to sublist."
7445 				sublist.push(nodeList.shift());
7446 
7447 				// "While the first member of node list is the nextSibling of the
7448 				// last member of sublist, remove the first member of node list and
7449 				// append it to sublist."
7450 				while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling) {
7451 					sublist.push(nodeList.shift());
7452 				}
7453 
7454 				// "Indent sublist."
7455 				indentNodes(sublist, newRange);
7456 			}
7457 		}
7458 	};
7459 
7460 	//@}
7461 	///// The insertHorizontalRule command /////
7462 	//@{
7463 	commands.inserthorizontalrule = {
7464 		action: function (value, range) {
7465 
7466 			// "While range's start offset is 0 and its start node's parent is not
7467 			// null, set range's start to (parent of start node, index of start
7468 			// node)."
7469 			while (range.startOffset == 0 && range.startContainer.parentNode) {
7470 				range.setStart(range.startContainer.parentNode, Dom.getIndexInParent(range.startContainer));
7471 			}
7472 
7473 			// "While range's end offset is the length of its end node, and its end
7474 			// node's parent is not null, set range's end to (parent of end node, 1
7475 			// + index of start node)."
7476 			while (range.endOffset == getNodeLength(range.endContainer) && range.endContainer.parentNode) {
7477 				range.setEnd(range.endContainer.parentNode, 1 + Dom.getIndexInParent(range.endContainer));
7478 			}
7479 
7480 			// "Delete the contents of range, with block merging false."
7481 			deleteContents(range, {
7482 				blockMerging: false
7483 			});
7484 
7485 			// "If the active range's start node is neither editable nor an editing
7486 			// host, abort these steps."
7487 			if (!isEditable(getActiveRange().startContainer) && !isEditingHost(getActiveRange().startContainer)) {
7488 				return;
7489 			}
7490 
7491 			// "If the active range's start node is a Text node and its start
7492 			// offset is zero, set the active range's start and end to (parent of
7493 			// start node, index of start node)."
7494 			if (getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset == 0) {
7495 				getActiveRange().setStart(getActiveRange().startContainer.parentNode, Dom.getIndexInParent(getActiveRange().startContainer));
7496 				getActiveRange().collapse(true);
7497 			}
7498 
7499 			// "If the active range's start node is a Text node and its start
7500 			// offset is the length of its start node, set the active range's start
7501 			// and end to (parent of start node, 1 + index of start node)."
7502 			if (getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset == getNodeLength(getActiveRange().startContainer)) {
7503 				getActiveRange().setStart(getActiveRange().startContainer.parentNode, 1 + Dom.getIndexInParent(getActiveRange().startContainer));
7504 				getActiveRange().collapse(true);
7505 			}
7506 
7507 			// "Let hr be the result of calling createElement("hr") on the
7508 			// context object."
7509 			var hr = document.createElement("hr");
7510 
7511 			// "Run insertNode(hr) on the range."
7512 			range.insertNode(hr);
7513 
7514 			// "Fix disallowed ancestors of hr."
7515 			fixDisallowedAncestors(hr, range);
7516 
7517 			// "Run collapse() on the Selection, with first argument equal to the
7518 			// parent of hr and the second argument equal to one plus the index of
7519 			// hr."
7520 			//
7521 			// Not everyone actually supports collapse(), so we do it manually
7522 			// instead.  Also, we need to modify the actual range we're given as
7523 			// well, for the sake of autoimplementation.html's range-filling-in.
7524 			range.setStart(hr.parentNode, 1 + Dom.getIndexInParent(hr));
7525 			range.setEnd(hr.parentNode, 1 + Dom.getIndexInParent(hr));
7526 			Aloha.getSelection().removeAllRanges();
7527 			Aloha.getSelection().addRange(range);
7528 		}
7529 	};
7530 
7531 	//@}
7532 	///// The insertHTML command /////
7533 	//@{
7534 	commands.inserthtml = {
7535 		action: function (value, range) {
7536 
7537 
7538 			// "Delete the contents of the active range."
7539 7540 			deleteContents(range);
7541 
7542 			// "If the active range's start node is neither editable nor an editing
7543 			// host, abort these steps."
7544 			if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) {
7545 				return;
7546 			}
7547 
7548 			// "Let frag be the result of calling createContextualFragment(value)
7549 			// on the active range."
7550 			var frag = range.createContextualFragment(value);
7551 
7552 			// "Let last child be the lastChild of frag."
7553 			var lastChild = frag.lastChild;
7554 
7555 			// "If last child is null, abort these steps."
7556 			if (!lastChild) {
7557 				return;
7558 			}
7559 
7560 			// "Let descendants be all descendants of frag."
7561 			var descendants = getDescendants(frag);
7562 
7563 			// "If the active range's start node is a block node:"
7564 			if (isBlockNode(range.startContainer)) {
7565 				// "Let collapsed block props be all editable collapsed block prop
7566 				// children of the active range's start node that have index
7567 				// greater than or equal to the active range's start offset."
7568 				//
7569 				// "For each node in collapsed block props, remove node from its
7570 				// parent."
7571 				$_(range.startContainer.childNodes).filter(function (node, range) {
7572 					return isEditable(node) && isCollapsedBlockProp(node) && Dom.getIndexInParent(node) >= range.startOffset;
7573 				}, true).forEach(function (node) {
7574 					node.parentNode.removeChild(node);
7575 				});
7576 			}
7577 
7578 			// "Call insertNode(frag) on the active range."
7579 			range.insertNode(frag);
7580 
7581 			// "If the active range's start node is a block node with no visible
7582 			// children, call createElement("br") on the context object and append
7583 			// the result as the last child of the active range's start node."
7584 			if (isBlockNode(range.startContainer)) {
7585 				ensureContainerEditable(range.startContainer);
7586 			}
7587 
7588 			// "Call collapse() on the context object's Selection, with last
7589 			// child's parent as the first argument and one plus its index as the
7590 			// second."
7591 			range.setStart(lastChild.parentNode, 1 + Dom.getIndexInParent(lastChild));
7592 			range.setEnd(lastChild.parentNode, 1 + Dom.getIndexInParent(lastChild));
7593 
7594 			// "Fix disallowed ancestors of each member of descendants."
7595 			var i;
7596 			for (i = 0; i < descendants.length; i++) {
7597 				fixDisallowedAncestors(descendants[i], range);
7598 			}
7599 
7600 			setActiveRange(range);
7601 		}
7602 	};
7603 
7604 	//@}
7605 	///// The insertImage command /////
7606 	//@{
7607 	commands.insertimage = {
7608 7609 		action: function (value) {
7610 			// "If value is the empty string, abort these steps and do nothing."
7611 			if (value === "") {
7612 				return;
7613 			}
7614 
7615 			// "Let range be the active range."
7616 			var range = getActiveRange();
7617 
7618 			// "Delete the contents of range, with strip wrappers false."
7619 			deleteContents(range, {
7620 				stripWrappers: false
7621 			});
7622 
7623 			// "If the active range's start node is neither editable nor an editing
7624 			// host, abort these steps."
7625 			if (!isEditable(getActiveRange().startContainer) && !isEditingHost(getActiveRange().startContainer)) {
7626 				return;
7627 			}
7628 
7629 			// "If range's start node is a block node whose sole child is a br, and
7630 			// its start offset is 0, remove its start node's child from it."
7631 			if (isBlockNode(range.startContainer) && range.startContainer.childNodes.length == 1 && isNamedHtmlElement(range.startContainer.firstChild, "br") && range.startOffset == 0) {
7632 				range.startContainer.removeChild(range.startContainer.firstChild);
7633 			}
7634 
7635 			// "Let img be the result of calling createElement("img") on the
7636 			// context object."
7637 			var img = document.createElement("img");
7638 
7639 			// "Run setAttribute("src", value) on img."
7640 			img.setAttribute("src", value);
7641 
7642 			// "Run insertNode(img) on the range."
7643 			range.insertNode(img);
7644 
7645 			// "Run collapse() on the Selection, with first argument equal to the
7646 			// parent of img and the second argument equal to one plus the index of
7647 			// img."
7648 			//
7649 			// Not everyone actually supports collapse(), so we do it manually
7650 			// instead.  Also, we need to modify the actual range we're given as
7651 			// well, for the sake of autoimplementation.html's range-filling-in.
7652 			range.setStart(img.parentNode, 1 + Dom.getIndexInParent(img));
7653 			range.setEnd(img.parentNode, 1 + Dom.getIndexInParent(img));
7654 			Aloha.getSelection().removeAllRanges();
7655 			Aloha.getSelection().addRange(range);
7656 
7657 			// IE adds width and height attributes for some reason, so remove those
7658 			// to actually do what the spec says.
7659 			img.removeAttribute("width");
7660 			img.removeAttribute("height");
7661 		}
7662 	};
7663 
7664 	//@}
7665 	///// The insertLineBreak command /////
7666 	//@{
7667 	commands.insertlinebreak = {
7668 		action: function (value, range) {
7669 			// "Delete the contents of the active range, with strip wrappers false."
7670 			deleteContents(range, {
7671 				stripWrappers: false
7672 			});
7673 
7674 			// "If the active range's start node is neither editable nor an editing
7675 			// host, abort these steps."
7676 			if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) {
7677 				return;
7678 			}
7679 
7680 			// "If the active range's start node is an Element, and "br" is not an
7681 			// allowed child of it, abort these steps."
7682 			if (range.startContainer.nodeType == $_.Node.ELEMENT_NODE && !isAllowedChild("br", range.startContainer)) {
7683 				return;
7684 			}
7685 
7686 			// "If the active range's start node is not an Element, and "br" is not
7687 			// an allowed child of the active range's start node's parent, abort
7688 			// these steps."
7689 			if (range.startContainer.nodeType != $_.Node.ELEMENT_NODE && !isAllowedChild("br", range.startContainer.parentNode)) {
7690 				return;
7691 			}
7692 
7693 			// "If the active range's start node is a Text node and its start
7694 			// offset is zero, call collapse() on the context object's Selection,
7695 			// with first argument equal to the active range's start node's parent
7696 			// and second argument equal to the active range's start node's index."
7697 			var newNode, newOffset;
7698 			if (range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset == 0) {
7699 				newNode = range.startContainer.parentNode;
7700 				newOffset = Dom.getIndexInParent(range.startContainer);
7701 				Aloha.getSelection().collapse(newNode, newOffset);
7702 				range.setStart(newNode, newOffset);
7703 				range.setEnd(newNode, newOffset);
7704 			}
7705 
7706 			// "If the active range's start node is a Text node and its start
7707 			// offset is the length of its start node, call collapse() on the
7708 			// context object's Selection, with first argument equal to the active
7709 			// range's start node's parent and second argument equal to one plus
7710 			// the active range's start node's index."
7711 			if (range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset == getNodeLength(range.startContainer)) {
7712 				newNode = range.startContainer.parentNode;
7713 				newOffset = 1 + Dom.getIndexInParent(range.startContainer);
7714 				Aloha.getSelection().collapse(newNode, newOffset);
7715 				range.setStart(newNode, newOffset);
7716 				range.setEnd(newNode, newOffset);
7717 			}
7718 
7719 			// "Let br be the result of calling createElement("br") on the context
7720 			// object."
7721 			var br = document.createElement("br");
7722 
7723 			// "Call insertNode(br) on the active range."
7724 			range.insertNode(br);
7725 
7726 			// "Call collapse() on the context object's Selection, with br's parent
7727 			// as the first argument and one plus br's index as the second
7728 			// argument."
7729 			Aloha.getSelection().collapse(br.parentNode, 1 + Dom.getIndexInParent(br));
7730 			range.setStart(br.parentNode, 1 + Dom.getIndexInParent(br));
7731 			range.setEnd(br.parentNode, 1 + Dom.getIndexInParent(br));
7732 
7733 			// "If br is a collapsed line break, call createElement("br") on the
7734 			// context object and let extra br be the result, then call
7735 			// insertNode(extra br) on the active range."
7736 			if (isCollapsedLineBreak(br)) {
7737 				// TODO
7738 				range.insertNode(createEndBreak());
7739 
7740 				// Compensate for nonstandard implementations of insertNode
7741 				Aloha.getSelection().collapse(br.parentNode, 1 + Dom.getIndexInParent(br));
7742 				range.setStart(br.parentNode, 1 + Dom.getIndexInParent(br));
7743 				range.setEnd(br.parentNode, 1 + Dom.getIndexInParent(br));
7744 			}
7745 
7746 			// IE7 is adding this styles: height: auto; min-height: 0px; max-height: none;
7747 			// with that there is the ugly "IE-editable-outline"
7748 			if (jQuery.browser.msie && jQuery.browser.version < 8) {
7749 				br.parentNode.removeAttribute("style");
7750 			}
7751 		}
7752 	};
7753 
7754 	//@}
7755 	///// The insertOrderedList command /////
7756 	//@{
7757 	commands.insertorderedlist = {
7758 		// "Toggle lists with tag name "ol"."
7759 		action: function (value, range) {
7760 			toggleLists("ol", range);
7761 		},
7762 		// "True if the selection's list state is "mixed" or "mixed ol", false
7763 		// otherwise."
7764 		indeterm: function () {
7765 			return (/^mixed( ol)?$/).test(getSelectionListState());
7766 		},
7767 		// "True if the selection's list state is "ol", false otherwise."
7768 		state: function () {
7769 			return getSelectionListState() == "ol";
7770 		}
7771 	};
7772 
7773 	var listRelatedElements = {
7774 		"LI": true,
7775 		"DT": true,
7776 		"DD": true
7777 	};
7778 
7779 	//@}
7780 	///// The insertParagraph command /////
7781 	//@{
7782 	commands.insertparagraph = {
7783 		action: function (value, range) {
7784 			var i;
7785 
7786 			// "Delete the contents of the active range."
7787 			deleteContents(range);
7788 
7789 			// clean lists in the editing host, this will remove any whitespace nodes around lists
7790 			// because the following algorithm is not prepared to deal with them
7791 			cleanLists(getEditingHostOf(range.startContainer), range);
7792 
7793 			// "If the active range's start node is neither editable nor an editing
7794 			// host, abort these steps."
7795 			if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) {
7796 				return;
7797 			}
7798 
7799 			// "Let node and offset be the active range's start node and offset."
7800 			var node = range.startContainer;
7801 			var offset = range.startOffset;
7802 
7803 			// "If node is a Text node, and offset is neither 0 nor the length of
7804 			// node, call splitText(offset) on node."
7805 			if (node.nodeType == $_.Node.TEXT_NODE && offset != 0 && offset != getNodeLength(node)) {
7806 				splitText(node, offset);
7807 			}
7808 
7809 			// "If node is a Text node and offset is its length, set offset to one
7810 			// plus the index of node, then set node to its parent."
7811 			if (node.nodeType == $_.Node.TEXT_NODE && offset == getNodeLength(node)) {
7812 				offset = 1 + Dom.getIndexInParent(node);
7813 				node = node.parentNode;
7814 			}
7815 
7816 			// "If node is a Text or Comment node, set offset to the index of node,
7817 			// then set node to its parent."
7818 			if (node.nodeType == $_.Node.TEXT_NODE || node.nodeType == $_.Node.COMMENT_NODE) {
7819 				offset = Dom.getIndexInParent(node);
7820 				node = node.parentNode;
7821 			}
7822 
7823 			// "Call collapse(node, offset) on the context object's Selection."
7824 			Aloha.getSelection().collapse(node, offset);
7825 			range.setStart(node, offset);
7826 			range.setEnd(node, offset);
7827 
7828 			// "Let container equal node."
7829 			var container = node;
7830 
7831 			// "While container is not a single-line container, and container's
7832 			// parent is editable and in the same editing host as node, set
7833 			// container to its parent."
7834 			while (!isSingleLineContainer(container) && isEditable(container.parentNode) && inSameEditingHost(node, container.parentNode)) {
7835 				container = container.parentNode;
7836 			}
7837 
7838 			// "If container is not editable or not in the same editing host as
7839 			// node or is not a single-line container:"
7840 			if (!isEditable(container) || !inSameEditingHost(container, node) || !isSingleLineContainer(container)) {
7841 				// "Let tag be the default single-line container name."
7842 				var tag = defaultSingleLineContainerName;
7843 
7844 				// "Block-extend the active range, and let new range be the
7845 				// result."
7846 				var newRange = blockExtend(range);
7847 
7848 				// "Let node list be a list of nodes, initially empty."
7849 				//
7850 				// "Append to node list the first node in tree order that is
7851 				// contained in new range and is an allowed child of "p", if any."
7852 				var nodeList = getContainedNodes(newRange, function (node) {
7853 					return isAllowedChild(node, "p");
7854 				}).slice(0, 1);
7855 
7856 				// "If node list is empty:"
7857 				if (!nodeList.length) {
7858 					// "If tag is not an allowed child of the active range's start
7859 					// node, abort these steps."
7860 					if (!isAllowedChild(tag, range.startContainer)) {
7861 						return;
7862 					}
7863 
7864 					// "Set container to the result of calling createElement(tag)
7865 					// on the context object."
7866 					container = document.createElement(tag);
7867 
7868 					// "Call insertNode(container) on the active range."
7869 					range.insertNode(container);
7870 
7871 					// "Call createElement("br") on the context object, and append
7872 					// the result as the last child of container."
7873 					// TODO not always
7874 					container.appendChild(createEndBreak());
7875 
7876 					// "Call collapse(container, 0) on the context object's
7877 					// Selection."
7878 					// TODO: remove selection from command
7879 					Aloha.getSelection().collapse(container, 0);
7880 					range.setStart(container, 0);
7881 					range.setEnd(container, 0);
7882 
7883 					// "Abort these steps."
7884 					return;
7885 				}
7886 
7887 				// "While the nextSibling of the last member of node list is not
7888 				// null and is an allowed child of "p", append it to node list."
7889 				while (nodeList[nodeList.length - 1].nextSibling && isAllowedChild(nodeList[nodeList.length - 1].nextSibling, "p")) {
7890 					nodeList.push(nodeList[nodeList.length - 1].nextSibling);
7891 				}
7892 
7893 				// "Wrap node list, with sibling criteria returning false and new
7894 				// parent instructions returning the result of calling
7895 				// createElement(tag) on the context object. Set container to the
7896 				// result."
7897 				container = wrap(
7898 					nodeList,
7899 					function () {
7900 						return false;
7901 					},
7902 					function () {
7903 						return document.createElement(tag);
7904 					},
7905 					range
7906 				);
7907 			}
7908 
7909 			// If no container has been set yet, it is not possible to insert a paragraph at this position;
7910 			// the following steps are skipped in order to prevent critical errors from occurring;
7911 			if (!container) {
7912 				return;
7913 			}
7914 
7915 			// "If container's local name is "address", "listing", or "pre":"
7916 7917 			var oldHeight, newHeight;
7918 			if (container.tagName == "ADDRESS" || container.tagName == "LISTING" || container.tagName == "PRE") {
7919 				// "Let br be the result of calling createElement("br") on the
7920 				// context object."
7921 				var br = document.createElement("br");
7922 
7923 				// remember the old height
7924 				oldHeight = container.offsetHeight;
7925 
7926 				// "Call insertNode(br) on the active range."
7927 				range.insertNode(br);
7928 
7929 				// determine the new height
7930 				newHeight = container.offsetHeight;
7931 
7932 				// "Call collapse(node, offset + 1) on the context object's
7933 				// Selection."
7934 				Aloha.getSelection().collapse(node, offset + 1);
7935 				range.setStart(node, offset + 1);
7936 				range.setEnd(node, offset + 1);
7937 
7938 				// "If br is the last descendant of container, let br be the result
7939 				// of calling createElement("br") on the context object, then call
7940 				// insertNode(br) on the active range." (Fix: only do this, if the container height did not change by inserting a single <br/>)
7941 				//
7942 				// Work around browser bugs: some browsers select the
7943 				// newly-inserted node, not per spec.
7944 				if (oldHeight == newHeight && !isDescendant(nextNode(br), container)) {
7945 					// TODO check
7946 					range.insertNode(createEndBreak());
7947 					Aloha.getSelection().collapse(node, offset + 1);
7948 					range.setEnd(node, offset + 1);
7949 				}
7950 
7951 				// "Abort these steps."
7952 				return;
7953 			}
7954 
7955 			// "If container's local name is "li", "dt", or "dd"; and either it has
7956 			// no children or it has a single child and that child is a br:"
7957 			if (listRelatedElements[container.tagName] && (!container.hasChildNodes() || (container.childNodes.length == 1 && isNamedHtmlElement(container.firstChild, "br")))) {
7958 				// "Split the parent of the one-node list consisting of container."
7959 				splitParent([container], range);
7960 
7961 				// "If container has no children, call createElement("br") on the
7962 				// context object and append the result as the last child of
7963 				// container."
7964 				// only do this, if inserting the br does NOT modify the offset height of the container
7965 				//			if (!container.hasChildNodes()) {
7966 				//				var oldHeight = container.offsetHeight, endBr = createEndBreak();
7967 				//				container.appendChild(endBr);
7968 				//				if (container.offsetHeight !== oldHeight) {
7969 				//					container.removeChild(endBr);
7970 				//				}
7971 				//			}
7972 
7973 				// "If container is a dd or dt, and it is not an allowed child of
7974 				// any of its ancestors in the same editing host, set the tag name
7975 				// of container to the default single-line container name and let
7976 				// container be the result."
7977 				if (isHtmlElementInArray(container, ["dd", "dt"]) && $_(getAncestors(container)).every(function (ancestor) { return !inSameEditingHost(container, ancestor) || !isAllowedChild(container, ancestor); })) {
7978 					container = setTagName(container, defaultSingleLineContainerName, range);
7979 				}
7980 
7981 				// "Fix disallowed ancestors of container."
7982 				fixDisallowedAncestors(container, range);
7983 
7984 				// fix invalid nested lists
7985 				if (isNamedHtmlElement(container, 'li') && isNamedHtmlElement(container.nextSibling, "li") && isHtmlElementInArray(container.nextSibling.firstChild, ["ol", "ul"])) {
7986 					// we found a li containing only a br followed by a li containing a list as first element: merge the two li's
7987 					var listParent = container.nextSibling,
7988 						length = container.nextSibling.childNodes.length;
7989 					for (i = 0; i < length; i++) {
7990 						// we always move the first child into the container
7991 						container.appendChild(listParent.childNodes[0]);
7992 					}
7993 					listParent.parentNode.removeChild(listParent);
7994 				}
7995 
7996 				// "Abort these steps."
7997 				return;
7998 			}
7999 
8000 			// special behaviour when pressing enter in the last empty paragraph, that is nested in a blockquote
8001 			if (isNamedHtmlElement(container, "p")
8002 					&& isNamedHtmlElement(container.parentNode, "blockquote")
8003 						&& !container.nextSibling
8004 							&& (!container.hasChildNodes()
8005 									|| (container.childNodes.length === 1
8006 											&& isNamedHtmlElement(container.firstChild, "br")))) {
8007 				jQuery(container.parentNode).after(container);
8008 				return;
8009 			}
8010 
8011 			// "Let new line range be a new range whose start is the same as
8012 			// the active range's, and whose end is (container, length of
8013 			// container)."
8014 			var newLineRange = Aloha.createRange();
8015 			newLineRange.setStart(range.startContainer, range.startOffset);
8016 			newLineRange.setEnd(container, getNodeLength(container));
8017 
8018 			// "While new line range's start offset is zero and its start node is
8019 			// not container, set its start to (parent of start node, index of
8020 			// start node)."
8021 			while (newLineRange.startOffset == 0 && newLineRange.startContainer != container) {
8022 				newLineRange.setStart(newLineRange.startContainer.parentNode, Dom.getIndexInParent(newLineRange.startContainer));
8023 			}
8024 
8025 			// "While new line range's start offset is the length of its start node
8026 			// and its start node is not container, set its start to (parent of
8027 			// start node, 1 + index of start node)."
8028 			while (newLineRange.startOffset == getNodeLength(newLineRange.startContainer) && newLineRange.startContainer != container) {
8029 				newLineRange.setStart(newLineRange.startContainer.parentNode, 1 + Dom.getIndexInParent(newLineRange.startContainer));
8030 			}
8031 
8032 			// "Let end of line be true if new line range contains either nothing
8033 			// or a single br, and false otherwise."
8034 			var containedInNewLineRange = getContainedNodes(newLineRange);
8035 			var endOfLine = !containedInNewLineRange.length || (containedInNewLineRange.length == 1 && isNamedHtmlElement(containedInNewLineRange[0], "br"));
8036 
8037 			// "If the local name of container is "h1", "h2", "h3", "h4", "h5", or
8038 			// "h6", and end of line is true, let new container name be the default
8039 			// single-line container name."
8040 			var newContainerName;
8041 			if (/^H[1-6]$/.test(container.tagName) && endOfLine) {
8042 				newContainerName = defaultSingleLineContainerName;
8043 
8044 				// "Otherwise, if the local name of container is "dt" and end of line
8045 				// is true, let new container name be "dd"."
8046 			} else if (container.tagName == "DT" && endOfLine) {
8047 				newContainerName = "dd";
8048 
8049 				// "Otherwise, if the local name of container is "dd" and end of line
8050 				// is true, let new container name be "dt"."
8051 			} else if (container.tagName == "DD" && endOfLine) {
8052 				newContainerName = "dt";
8053 
8054 				// "Otherwise, let new container name be the local name of container."
8055 			} else {
8056 				newContainerName = container.tagName.toLowerCase();
8057 			}
8058 
8059 			// "Let new container be the result of calling createElement(new
8060 			// container name) on the context object."
8061 			var newContainer = document.createElement(newContainerName);
8062 
8063 			// "Copy all non empty attributes of the container to new container."
8064 			copyAttributes(container, newContainer);
8065 
8066 			// "If new container has an id attribute, unset it."
8067 			newContainer.removeAttribute("id");
8068 
8069 			// "Insert new container into the parent of container immediately after
8070 			// container."
8071 			container.parentNode.insertBefore(newContainer, container.nextSibling);
8072 
8073 			// "Let contained nodes be all nodes contained in new line range."
8074 			var containedNodes = getAllContainedNodes(newLineRange);
8075 
8076 			// "Let frag be the result of calling extractContents() on new line
8077 			// range."
8078 			var frag = newLineRange.extractContents();
8079 
8080 			// "Unset the id attribute (if any) of each Element descendant of frag
8081 			// that is not in contained nodes."
8082 			var descendants = getDescendants(frag);
8083 			for (i = 0; i < descendants.length; i++) {
8084 				if (descendants[i].nodeType == $_.Node.ELEMENT_NODE && $_(containedNodes).indexOf(descendants[i]) == -1) {
8085 					descendants[i].removeAttribute("id");
8086 				}
8087 			}
8088 
8089 			var fragChildren = [],
8090 				fragChild = frag.firstChild;
8091 			if (fragChild) {
8092 				do {
8093 					if (!isWhitespaceNode(fragChild)) {
8094 						fragChildren.push(fragChild);
8095 					}
8096 				} while (null != (fragChild = fragChild.nextSibling));
8097 			}
8098 
8099 			// if newContainer is a li and frag contains only a list, we add a br in the li (but only if the height would not change)
8100 			if (isNamedHtmlElement(newContainer, 'li') && fragChildren.length && isHtmlElementInArray(fragChildren[0], ["ul", "ol"])) {
8101 				oldHeight = newContainer.offsetHeight;
8102 				var endBr = createEndBreak();
8103 				newContainer.appendChild(endBr);
8104 				newHeight = newContainer.offsetHeight;
8105 				if (oldHeight !== newHeight) {
8106 					newContainer.removeChild(endBr);
8107 				}
8108 			}
8109 
8110 			// "Call appendChild(frag) on new container."
8111 			newContainer.appendChild(frag);
8112 
8113 			// "If container has no visible children, call createElement("br") on
8114 			// the context object, and append the result as the last child of
8115 			// container."
8116 			ensureContainerEditable(container);
8117 
8118 			// "If new container has no visible children, call createElement("br")
8119 			// on the context object, and append the result as the last child of
8120 			// new container."
8121 			ensureContainerEditable(newContainer);
8122 
8123 			// "Call collapse(new container, 0) on the context object's Selection."
8124 			Aloha.getSelection().collapse(newContainer, 0);
8125 			range.setStart(newContainer, 0);
8126 			range.setEnd(newContainer, 0);
8127 		}
8128 	};
8129 
8130 	//@}
8131 	///// The insertText command /////
8132 	//@{
8133 	commands.inserttext = {
8134 		action: function (value, range) {
8135 			var i;
8136 
8137 			// "Delete the contents of the active range, with strip wrappers
8138 			// false."
8139 			deleteContents(range, {
8140 				stripWrappers: false
8141 			});
8142 
8143 			// "If the active range's start node is neither editable nor an editing
8144 			// host, abort these steps."
8145 			if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) {
8146 				return;
8147 			}
8148 
8149 			// "If value's length is greater than one:"
8150 			if (value.length > 1) {
8151 				// "For each element el in value, take the action for the
8152 				// insertText command, with value equal to el."
8153 				for (i = 0; i < value.length; i++) {
8154 					commands.inserttext.action(value[i], range);
8155 				}
8156 
8157 				// "Abort these steps."
8158 				return;
8159 			}
8160 
8161 			// "If value is the empty string, abort these steps."
8162 			if (value == "") {
8163 				return;
8164 			}
8165 
8166 			// "If value is a newline (U+00A0), take the action for the
8167 			// insertParagraph command and abort these steps."
8168 			if (value == "\n") {
8169 				commands.insertparagraph.action('', range);
8170 				return;
8171 			}
8172 
8173 			// "Let node and offset be the active range's start node and offset."
8174 			var node = range.startContainer;
8175 			var offset = range.startOffset;
8176 
8177 			// "If node has a child whose index is offset − 1, and that child is a
8178 			// Text node, set node to that child, then set offset to node's
8179 			// length."
8180 			if (0 <= offset - 1 && offset - 1 < node.childNodes.length && node.childNodes[offset - 1].nodeType == $_.Node.TEXT_NODE) {
8181 				node = node.childNodes[offset - 1];
8182 				offset = getNodeLength(node);
8183 			}
8184 
8185 			// "If node has a child whose index is offset, and that child is a Text
8186 			// node, set node to that child, then set offset to zero."
8187 			if (0 <= offset && offset < node.childNodes.length && node.childNodes[offset].nodeType == $_.Node.TEXT_NODE) {
8188 				node = node.childNodes[offset];
8189 				offset = 0;
8190 			}
8191 
8192 			// "If value is a space (U+0020), and either node is an Element whose
8193 			// resolved value for "white-space" is neither "pre" nor "pre-wrap" or
8194 			// node is not an Element but its parent is an Element whose resolved
8195 			// value for "white-space" is neither "pre" nor "pre-wrap", set value
8196 			// to a non-breaking space (U+00A0)."
8197 			var refElement = node.nodeType == $_.Node.ELEMENT_NODE ? node : node.parentNode;
8198 			if (value == " " && refElement.nodeType == $_.Node.ELEMENT_NODE && jQuery.inArray($_.getComputedStyle(refElement).whiteSpace, ["pre", "pre-wrap"]) == -1) {
8199 				value = "\xa0";
8200 			}
8201 
8202 			// "Record current overrides, and let overrides be the result."
8203 			var overrides = recordCurrentOverrides(range);
8204 
8205 			// "If node is a Text node:"
8206 			if (node.nodeType == $_.Node.TEXT_NODE) {
8207 				// "Call insertData(offset, value) on node."
8208 				node.insertData(offset, value);
8209 
8210 				// "Call collapse(node, offset) on the context object's Selection."
8211 				Aloha.getSelection().collapse(node, offset);
8212 				range.setStart(node, offset);
8213 
8214 				// "Call extend(node, offset + 1) on the context object's
8215 				// Selection."
8216 				Aloha.getSelection().extend(node, offset + 1);
8217 				range.setEnd(node, offset + 1);
8218 
8219 				// "Otherwise:"
8220 			} else {
8221 				// "If node has only one child, which is a collapsed line break,
8222 				// remove its child from it."
8223 				//
8224 				// FIXME: IE incorrectly returns false here instead of true
8225 				// sometimes?
8226 				if (node.childNodes.length == 1 && isCollapsedLineBreak(node.firstChild)) {
8227 					node.removeChild(node.firstChild);
8228 				}
8229 
8230 				// "Let text be the result of calling createTextNode(value) on the
8231 				// context object."
8232 				var text = document.createTextNode(value);
8233 
8234 				// "Call insertNode(text) on the active range."
8235 				range.insertNode(text);
8236 
8237 				// "Call collapse(text, 0) on the context object's Selection."
8238 				Aloha.getSelection().collapse(text, 0);
8239 				range.setStart(text, 0);
8240 
8241 				// "Call extend(text, 1) on the context object's Selection."
8242 				Aloha.getSelection().extend(text, 1);
8243 				range.setEnd(text, 1);
8244 			}
8245 
8246 			// "Restore states and values from overrides."
8247 			restoreStatesAndValues(overrides, range);
8248 
8249 			// "Canonicalize whitespace at the active range's start."
8250 			canonicalizeWhitespace(range.startContainer, range.startOffset);
8251 
8252 			// "Canonicalize whitespace at the active range's end."
8253 			canonicalizeWhitespace(range.endContainer, range.endOffset);
8254 
8255 			// "Call collapseToEnd() on the context object's Selection."
8256 			Aloha.getSelection().collapseToEnd();
8257 			range.collapse(false);
8258 		}
8259 	};
8260 
8261 	//@}
8262 	///// The insertUnorderedList command /////
8263 	//@{
8264 	commands.insertunorderedlist = {
8265 		// "Toggle lists with tag name "ul"."
8266 		action: function (value, range) {
8267 			toggleLists("ul", range);
8268 		},
8269 		// "True if the selection's list state is "mixed" or "mixed ul", false
8270 		// otherwise."
8271 		indeterm: function () {
8272 			return (/^mixed( ul)?$/).test(getSelectionListState());
8273 		},
8274 		// "True if the selection's list state is "ul", false otherwise."
8275 		state: function () {
8276 			return getSelectionListState() == "ul";
8277 		}
8278 	};
8279 
8280 	//@}
8281 	///// The justifyCenter command /////
8282 	//@{
8283 	commands.justifycenter = {
8284 		// "Justify the selection with alignment "center"."
8285 		action: function (value, range) {
8286 			justifySelection("center", range);
8287 		},
8288 		indeterm: function () {
8289 			// "Block-extend the active range. Return true if among visible
8290 			// editable nodes that are contained in the result and have no
8291 			// children, at least one has alignment value "center" and at least one
8292 			// does not. Otherwise return false."
8293 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8294 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8295 			});
8296 			return $_(nodes).some(function (node) { return getAlignmentValue(node) == "center"; })
8297 				&& $_(nodes).some(function (node) { return getAlignmentValue(node) != "center"; });
8298 		},
8299 		state: function () {
8300 			// "Block-extend the active range. Return true if there is at least one
8301 			// visible editable node that is contained in the result and has no
8302 			// children, and all such nodes have alignment value "center".
8303 			// Otherwise return false."
8304 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8305 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8306 			});
8307 			return nodes.length && $_(nodes).every(function (node) {
8308 				return getAlignmentValue(node) == "center";
8309 			});
8310 		},
8311 		value: function () {
8312 			// "Block-extend the active range, and return the alignment value of
8313 			// the first visible editable node that is contained in the result and
8314 			// has no children. If there is no such node, return "left"."
8315 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8316 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8317 			});
8318 			if (nodes.length) {
8319 				return getAlignmentValue(nodes[0]);
8320 			}
8321 			return "left";
8322 		}
8323 	};
8324 
8325 	//@}
8326 	///// The justifyFull command /////
8327 	//@{
8328 	commands.justifyfull = {
8329 		// "Justify the selection with alignment "justify"."
8330 		action: function (value, range) {
8331 			justifySelection("justify", range);
8332 		},
8333 		indeterm: function () {
8334 			// "Block-extend the active range. Return true if among visible
8335 			// editable nodes that are contained in the result and have no
8336 			// children, at least one has alignment value "justify" and at least
8337 			// one does not. Otherwise return false."
8338 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8339 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8340 			});
8341 			return $_(nodes).some(function (node) { return getAlignmentValue(node) == "justify"; })
8342 				&& $_(nodes).some(function (node) { return getAlignmentValue(node) != "justify"; });
8343 		},
8344 		state: function () {
8345 			// "Block-extend the active range. Return true if there is at least one
8346 			// visible editable node that is contained in the result and has no
8347 			// children, and all such nodes have alignment value "justify".
8348 			// Otherwise return false."
8349 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8350 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8351 			});
8352 			return nodes.length && $_(nodes).every(function (node) {
8353 				return getAlignmentValue(node) == "justify";
8354 			});
8355 		},
8356 		value: function () {
8357 			// "Block-extend the active range, and return the alignment value of
8358 			// the first visible editable node that is contained in the result and
8359 			// has no children. If there is no such node, return "left"."
8360 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8361 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8362 			});
8363 			if (nodes.length) {
8364 				return getAlignmentValue(nodes[0]);
8365 			}
8366 			return "left";
8367 		}
8368 	};
8369 
8370 	//@}
8371 	///// The justifyLeft command /////
8372 	//@{
8373 	commands.justifyleft = {
8374 		// "Justify the selection with alignment "left"."
8375 		action: function (value, range) {
8376 			justifySelection("left", range);
8377 		},
8378 		indeterm: function () {
8379 			// "Block-extend the active range. Return true if among visible
8380 			// editable nodes that are contained in the result and have no
8381 			// children, at least one has alignment value "left" and at least one
8382 			// does not. Otherwise return false."
8383 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8384 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8385 			});
8386 			return $_(nodes).some(function (node) { return getAlignmentValue(node) == "left"; })
8387 				&& $_(nodes).some(function (node) { return getAlignmentValue(node) != "left"; });
8388 		},
8389 		state: function () {
8390 			// "Block-extend the active range. Return true if there is at least one
8391 			// visible editable node that is contained in the result and has no
8392 			// children, and all such nodes have alignment value "left".  Otherwise
8393 			// return false."
8394 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8395 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8396 			});
8397 			return nodes.length && $_(nodes).every(function (node) {
8398 				return getAlignmentValue(node) == "left";
8399 			});
8400 		},
8401 		value: function () {
8402 			// "Block-extend the active range, and return the alignment value of
8403 			// the first visible editable node that is contained in the result and
8404 			// has no children. If there is no such node, return "left"."
8405 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8406 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8407 			});
8408 			if (nodes.length) {
8409 				return getAlignmentValue(nodes[0]);
8410 			}
8411 			return "left";
8412 		}
8413 	};
8414 
8415 	//@}
8416 	///// The justifyRight command /////
8417 	//@{
8418 	commands.justifyright = {
8419 		// "Justify the selection with alignment "right"."
8420 		action: function (value, range) {
8421 			justifySelection("right", range);
8422 		},
8423 		indeterm: function () {
8424 			// "Block-extend the active range. Return true if among visible
8425 			// editable nodes that are contained in the result and have no
8426 			// children, at least one has alignment value "right" and at least one
8427 			// does not. Otherwise return false."
8428 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8429 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8430 			});
8431 			return $_(nodes).some(function (node) { return getAlignmentValue(node) == "right"; })
8432 				&& $_(nodes).some(function (node) { return getAlignmentValue(node) != "right"; });
8433 		},
8434 		state: function () {
8435 			// "Block-extend the active range. Return true if there is at least one
8436 			// visible editable node that is contained in the result and has no
8437 			// children, and all such nodes have alignment value "right".
8438 			// Otherwise return false."
8439 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8440 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8441 			});
8442 			return nodes.length && $_(nodes).every(function (node) {
8443 				return getAlignmentValue(node) == "right";
8444 			});
8445 		},
8446 		value: function () {
8447 			// "Block-extend the active range, and return the alignment value of
8448 			// the first visible editable node that is contained in the result and
8449 			// has no children. If there is no such node, return "left"."
8450 			var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) {
8451 				return isEditable(node) && isVisible(node) && !node.hasChildNodes();
8452 			});
8453 			if (nodes.length) {
8454 				return getAlignmentValue(nodes[0]);
8455 			}
8456 			return "left";
8457 		}
8458 	};
8459 
8460 	//@}
8461 	///// The outdent command /////
8462 	//@{
8463 	commands.outdent = {
8464 		action: function () {
8465 			// "Let items be a list of all lis that are ancestor containers of the
8466 			// range's start and/or end node."
8467 			//
8468 			// It's annoying to get this in tree order using functional stuff
8469 			// without doing getDescendants(document), which is slow, so I do it
8470 			// imperatively.
8471 			var items = [];
8472 			(function () {
8473 				var ancestorContainer;
8474 				for (ancestorContainer = getActiveRange().endContainer;
8475 					     ancestorContainer != getActiveRange().commonAncestorContainer;
8476 					     ancestorContainer = ancestorContainer.parentNode) {
8477 					if (isNamedHtmlElement(ancestorContainer, "li")) {
8478 						items.unshift(ancestorContainer);
8479 					}
8480 				}
8481 				for (ancestorContainer = getActiveRange().startContainer;
8482 					     ancestorContainer;
8483 					     ancestorContainer = ancestorContainer.parentNode) {
8484 					if (isNamedHtmlElement(ancestorContainer, "li")) {
8485 						items.unshift(ancestorContainer);
8486 					}
8487 				}
8488 			}());
8489 
8490 			// "For each item in items, normalize sublists of item."
8491 			$_(items).forEach(function (thisArg) {
8492 				normalizeSublists(thisArg, getActiveRange());
8493 			});
8494 
8495 			// "Block-extend the active range, and let new range be the result."
8496 			var newRange = blockExtend(getActiveRange());
8497 
8498 			// "Let node list be a list of nodes, initially empty."
8499 			//
8500 			// "For each node node contained in new range, append node to node list
8501 			// if the last member of node list (if any) is not an ancestor of node;
8502 			// node is editable; and either node has no editable descendants, or is
8503 			// an ol or ul, or is an li whose parent is an ol or ul."
8504 			var nodeList = getContainedNodes(newRange, function (node) {
8505 				return isEditable(node) && (!$_(getDescendants(node)).some(isEditable) || isHtmlElementInArray(node, ["ol", "ul"]) || (isNamedHtmlElement(node, 'li') && isHtmlElementInArray(node.parentNode, ["ol", "ul"])));
8506 			});
8507 
8508 			// "While node list is not empty:"
8509 			while (nodeList.length) {
8510 				// "While the first member of node list is an ol or ul or is not
8511 				// the child of an ol or ul, outdent it and remove it from node
8512 				// list."
8513 				while (nodeList.length && (isHtmlElementInArray(nodeList[0], ["OL", "UL"]) || !isHtmlElementInArray(nodeList[0].parentNode, ["OL", "UL"]))) {
8514 					outdentNode(nodeList.shift(), newRange);
8515 				}
8516 
8517 				// "If node list is empty, break from these substeps."
8518 				if (!nodeList.length) {
8519 					break;
8520 				}
8521 
8522 				// "Let sublist be a list of nodes, initially empty."
8523 				var sublist = [];
8524 
8525 				// "Remove the first member of node list and append it to sublist."
8526 				sublist.push(nodeList.shift());
8527 
8528 				// "While the first member of node list is the nextSibling of the
8529 				// last member of sublist, and the first member of node list is not
8530 				// an ol or ul, remove the first member of node list and append it
8531 				// to sublist."
8532 				while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isHtmlElementInArray(nodeList[0], ["OL", "UL"])) {
8533 					sublist.push(nodeList.shift());
8534 				}
8535 
8536 				// "Record the values of sublist, and let values be the result."
8537 				var values = recordValues(sublist);
8538 
8539 				// "Split the parent of sublist, with new parent null."
8540 				splitParent(sublist, newRange);
8541 
8542 				// "Fix disallowed ancestors of each member of sublist."
8543 				$_(sublist).forEach(fixDisallowedAncestors);
8544 
8545 				// "Restore the values from values."
8546 				restoreValues(values, newRange);
8547 			}
8548 		}
8549 	};
8550 
8551 	//@}
8552 
8553 	//////////////////////////////////
8554 	///// Miscellaneous commands /////
8555 	//////////////////////////////////
8556 
8557 	///// The selectAll command /////
8558 	//@{
8559 	commands.selectall = {
8560 		// Note, this ignores the whole globalRange/getActiveRange() thing and
8561 		// works with actual selections.  Not suitable for autoimplementation.html.
8562 		action: function () {
8563 			// "Let target be the body element of the context object."
8564 			var target = document.body;
8565 
8566 			// "If target is null, let target be the context object's
8567 			// documentElement."
8568 			if (!target) {
8569 				target = document.documentElement;
8570 			}
8571 
8572 			// "If target is null, call getSelection() on the context object, and
8573 			// call removeAllRanges() on the result."
8574 			if (!target) {
8575 				Aloha.getSelection().removeAllRanges();
8576 
8577 				// "Otherwise, call getSelection() on the context object, and call
8578 				// selectAllChildren(target) on the result."
8579 			} else {
8580 				Aloha.getSelection().selectAllChildren(target);
8581 			}
8582 		}
8583 	};
8584 
8585 	//@}
8586 	///// The styleWithCSS command /////
8587 	//@{
8588 	commands.stylewithcss = {
8589 		action: function (value) {
8590 			// "If value is an ASCII case-insensitive match for the string
8591 			// "false", set the CSS styling flag to false. Otherwise, set the
8592 			// CSS styling flag to true."
8593 			cssStylingFlag = String(value).toLowerCase() != "false";
8594 		},
8595 		state: function () {
8596 			return cssStylingFlag;
8597 		}
8598 	};
8599 
8600 	//@}
8601 	///// The useCSS command /////
8602 	//@{
8603 	commands.usecss = {
8604 		action: function (value) {
8605 			// "If value is an ASCII case-insensitive match for the string "false",
8606 			// set the CSS styling flag to true. Otherwise, set the CSS styling
8607 			// flag to false."
8608 			cssStylingFlag = String(value).toLowerCase() == "false";
8609 		}
8610 	};
8611 	//@}
8612 
8613 	// Some final setup
8614 	//@{
8615 	(function () {
8616 8617 		// Opera 11.50 doesn't implement Object.keys, so I have to make an explicit
8618 		// temporary, which means I need an extra closure to not leak the temporaries
8619 		// into the global namespace.  >:(
8620 		var commandNames = [];
8621 		var command;
8622 		for (command in commands) {
8623 			if (commands.hasOwnProperty(command)) {
8624 				commandNames.push(command);
8625 			}
8626 		}
8627 		$_(commandNames).forEach(function (command) {
8628 			// "If a command does not have a relevant CSS property specified, it
8629 			// defaults to null."
8630 			if (null == commands[command].relevantCssProperty) {
8631 				commands[command].relevantCssProperty = null;
8632 			}
8633 
8634 			// "If a command has inline command activated values defined but
8635 			// nothing else defines when it is indeterminate, it is indeterminate
8636 			// if among editable Text nodes effectively contained in the active
8637 			// range, there is at least one whose effective command value is one of
8638 			// the given values and at least one whose effective command value is
8639 			// not one of the given values."
8640 			if (null != commands[command].inlineCommandActivatedValues && null == commands[command].indeterm) {
8641 				commands[command].indeterm = function (range) {
8642 					var values = $_(getAllEffectivelyContainedNodes(range, function (node) { return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; }))
8643 						.map(function (node) { return getEffectiveCommandValue(node, command); });
8644 
8645 					var matchingValues = $_(values).filter(function (value) {
8646 						return $_(commands[command].inlineCommandActivatedValues).indexOf(value) != -1;
8647 					});
8648 
8649 					return matchingValues.length >= 1 && values.length - matchingValues.length >= 1;
8650 				};
8651 			}
8652 
8653 			// "If a command has inline command activated values defined, its state
8654 			// is true if either no editable Text node is effectively contained in
8655 			// the active range, and the active range's start node's effective
8656 			// command value is one of the given values; or if there is at least
8657 			// one editable Text node effectively contained in the active range,
8658 			// and all of them have an effective command value equal to one of the
8659 			// given values."
8660 			if (null != commands[command].inlineCommandActivatedValues) {
8661 				commands[command].state = function (range) {
8662 					var nodes = getAllEffectivelyContainedNodes(range, function (node) {
8663 						return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
8664 					});
8665 
8666 					if (nodes.length == 0) {
8667 						return $_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(range.startContainer, command)) != -1;
8668 					}
8669 					return $_(nodes).every(function (node) {
8670 						return $_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(node, command)) != -1;
8671 					});
8672 				};
8673 			}
8674 
8675 			// "If a command is a standard inline value command, it is
8676 			// indeterminate if among editable Text nodes that are effectively
8677 			// contained in the active range, there are two that have distinct
8678 			// effective command values. Its value is the effective command value
8679 			// of the first editable Text node that is effectively contained in the
8680 			// active range, or if there is no such node, the effective command
8681 			// value of the active range's start node."
8682 			if (null != commands[command].standardInlineValueCommand) {
8683 				commands[command].indeterm = function () {
8684 					var values = $_(getAllEffectivelyContainedNodes(getActiveRange())).filter(function (node) { return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; }, true)
8685 						.map(function (node) { return getEffectiveCommandValue(node, command); });
8686 					var i;
8687 					for (i = 1; i < values.length; i++) {
8688 						if (values[i] != values[i - 1]) {
8689 							return true;
8690 						}
8691 					}
8692 					return false;
8693 				};
8694 
8695 				commands[command].value = function (range) {
8696 					var refNode = getAllEffectivelyContainedNodes(range, function (node) {
8697 						return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE;
8698 					})[0];
8699 
8700 					if (typeof refNode == "undefined") {
8701 						refNode = range.startContainer;
8702 					}
8703 
8704 					return getEffectiveCommandValue(refNode, command);
8705 				};
8706 			}
8707 		});
8708 	}());
8709 	//@}
8710 	return {
8711 		commands: commands,
8712 		execCommand: myExecCommand,
8713 		queryCommandIndeterm: myQueryCommandIndeterm,
8714 		queryCommandState: myQueryCommandState,
8715 		queryCommandValue: myQueryCommandValue,
8716 		queryCommandEnabled: myQueryCommandEnabled,
8717 		queryCommandSupported: myQueryCommandSupported,
8718 		copyAttributes: copyAttributes,
8719 		createEndBreak: createEndBreak,
8720 		isEndBreak: isEndBreak,
8721 		ensureContainerEditable: ensureContainerEditable,
8722 		isEditingHost: isEditingHost,
8723 		isEditable: isEditable,
8724 		getStateOverride: getStateOverride,
8725 		setStateOverride: setStateOverride,
8726 		resetOverrides: resetOverrides,
8727 		unsetStateOverride: unsetStateOverride
8728 	};
8729 }); // end define
8730 // vim: foldmarker=@{,@} foldmethod=marker
8731