Status of this Document
The features documented herein are obsolete. Authors should not use these features directly, but instead use JavaScript editing libraries. The features described in this document are not implemented consistently or fully by user agents, and it is not expected that this will change in the foreseeable future.
This document aims to assist web browser implementers in correctly handling old websites, but implementers should be aware that it is incomplete and does not match any implementation exactly, so it is unlikely to process sites correctly as-is. Nevertheless it remains available in case the research that went into it proves useful to implementers.
Because of lack of implementer interest, this document is no longer maintained. However, the accompanying conformance tests are useful for regression-testing changes to existing editor implementations, even if those implementations do not intend to match the specification exactly.
The selections portion of this specification has been superseded by the Selection API specification. It remains here as well only to avoid the need to rewrite the editing portions of this specification to refer to the new specification.
This document is a rough draft of a specification for HTML editing APIs,
mainly defining selections, execCommand() and related
functionality. It replaces a couple of old sections of the HTML specification, and the selection
part of the old DOM Range specification.
Copyright © 2015 the Contributors to the HTML Editing APIs Specification, published by the W3C Editing APIs Community Group under the W3C Community Contributor License Agreement (CLA). A human-readable summary is available.
This specification, along with the accompanying JavaScript implementation and tests, may also be used under the terms of the CC0 1.0 Universal License. Thus anyone may reuse, modify, and redistribute them without restriction.
This specification was published by the W3C Editing APIs Community Group. It is not a W3C Standard nor is it on the W3C Standards Track. Please note that under the W3C Community Contributor License Agreement (CLA) there is a limited opt-out and other conditions apply. Learn more about W3C Community and Business Groups.
Table of contents
- Status of this Document
- Table of contents
- Introduction
- Tests
- Issues
- Selections
- Commands
- Methods to query and execute commands
- Common definitions
- Common algorithms
- Inline formatting commands
- Inline formatting command definitions
- Assorted inline formatting command algorithms
- Clearing an element's value
- Pushing down values
- Forcing the value of a node
- Setting the selection's value
- The
backColorcommand - The
boldcommand - The
createLinkcommand - The
fontNamecommand - The
fontSizecommand - The
foreColorcommand - The
hiliteColorcommand - The
italiccommand - The
removeFormatcommand - The
strikethroughcommand - The
subscriptcommand - The
superscriptcommand - The
underlinecommand - The
unlinkcommand
- Block formatting commands
- Block formatting command definitions
- Assorted block formatting command algorithms
- Block-extending a range
- Recording and restoring overrides
- Deleting the selection
- Splitting a node list's parent
- Canonical space sequences
- Indenting and outdenting
- Toggling lists
- Justifying the selection
- Automatic linking
- The
deletecommand - The
formatBlockcommand - The
forwardDeletecommand - The
indentcommand - The
insertHorizontalRulecommand - The
insertHTMLcommand - The
insertImagecommand - The
insertLineBreakcommand - The
insertOrderedListcommand - The
insertParagraphcommand - The
insertTextcommand - The
insertUnorderedListcommand - The
justifyCentercommand - The
justifyFullcommand - The
justifyLeftcommand - The
justifyRightcommand - The
outdentcommand
- Miscellaneous commands
- Additional requirements
- Acknowledgements
Introduction
A piece of software that claims to implement this specification must follow every normative requirement in it. Every requirement in this specification is normative unless stated otherwise.
This is a note. All notes other than this one are non-normative.
This is an open issue. All issues other than this one are non-normative.
The remainder of this section is not normative, and nor is any preceding section.
This specification defines commands to edit HTML documents programmatically. The APIs specified here were originally introduced in Microsoft's Internet Explorer, but have subsequently been copied by other browsers in a haphazard and imprecise fashion. Although the behavior specified here does not exactly match any browser at the time of writing, it can serve as a target to converge to in the future.
Where the reasoning behind the specification is of interest, such as when major preexisting rendering engines are known not to match it, the reasoning is available by clicking the "comments" button on the right (requires JavaScript). If you have questions about why the specification says something, check the comments first. They're sometimes longer than the specification text itself, and commonly record what the major browsers do and other essential information.
The principles I've used for writing this specification so far are:
- If all browsers that implement a particular feature agree on some detail of how it works, match them unless there's very good reason not to. When it's not clear what behavior is best, try to follow the implementations with the most market share. But if one browser's behavior is clearly better than the others', go with the better behavior.
- If a command is issued to format some text in a particular way, we will format the text that way no matter what. If the user clicks the "bold" button, they don't care that the text didn't become bold because of an external CSS rule or for any other reason, they only care that it didn't work. The only exception (beyond where it's simply impossible, like propagated text-decorations we can't remove) is that we don't try to override !important rules from external stylesheets, although we also don't go out of our way to respect them.
- When we're given a presentational command like "bold", don't modify
anything other than presentational markup related to that command. If an
element has non-presentational attributes like id or class, don't split it up
or remove it or anything. At most convert it to a span, if it's some type of
presentational element. ("Presentational" here really means "browsers
produce it in response to execCommand() so we need to treat it as
presentational", so it includes things like
strongandem.) Of course, in some cases we have to remove elements, like when merging two blocks. - Don't interfere with more markup than necessary. If the user modifies only a small run of text, don't go around simplifying ancestors or siblings or whatever unless it's necessary to produce simpler markup in the place that was actually modified.
- But if we are already changing around something's style, convert existing
styles to the preferred format. For instance, we use
<b>for bold (if the CSS styling flag is false), and convert<strong>and<span style="font-weight: bold">if we happen to be modifying that node anyway. - Try not to make the document less conforming than it originally was. If we happen to make it more conforming, good, although we don't have to go out of our way to do that. In some cases we do make the document less conforming, generally because there's some clear use-case that requires it or because it matches existing browsers behavior. (For instance, see the styleWithCSS = false mode, and the fact that insertImage doesn't add an alt attribute, etc.)
- Keep the markup as concise as possible. (I've received feedback that this is very important to authors.) Ideally, the markup should look as simple and neat as what a human would have produced by hand-editing. We do complicated manipulation to pull styles down from ancestors rather than having to use inline CSS, and make sure to tidy up any styles on elements that we happen to be modifying anyway. Previous principles take precedence over this one, however.
Tests
This section is not normative.
There are two groups of tests currently associated with this document: selection tests, and command tests. These tests are a non-normative part of this specification. The command tests are available in two formats, development tests and conformance tests. This has a lot to do with the history of how the specification was developed: selection was originally part of the defunct DOM Range spec, while the command parts were developed on their own. The selection things have been merged into the command spec, but neither the spec text nor the tests have been fully unified at the time of this writing.
Thus the selection tests live in their own directory, selecttest/. They use the standard testharness.js framework developed by James Graham. They're entirely self-contained, sharing nothing with the command tests (except invoking the testharness.js library). At the time of this writing, they're not nearly as comprehensive as the command tests, although they do test some functionality comprehensively.
On the other hand, the command-related part of this specification is developed in tandem with a more or less complete JavaScript implementation. The implementation is used for creating tests, of two different types: development tests and conformance tests. The two types of test share most of the same code, starting with the multi-thousand-line implementation itself. The actual tests run are largely the same in either case, but the way they're run is very different.
The development tests were the original ones, and were designed to assist in writing the specification from scratch. Given an input, they print out the spec's and browser's output to allow manual inspection. They can store the spec's output and will raise an alert if it changed since the last run, as a form of regression testing, but they don't print out counts of passed/failed tests. They are not designed to run exactly the same across browsers and are tolerant of minor variations. Development tests are likely not very useful for anyone other than the spec's editor.
Conformance tests were added later. They run the same tests as the development tests, but in an entirely non-interactive format, using the testharness.js framework like the selection tests. They always run the same set of tests, don't vary behavior between browsers (hopefully), and are unforgiving of any deviation. However, they're significantly more cumbersome to set up and use, so they're less useful for developing the specification itself.
There's a suite of predefined tests for each command (~30–300 at the time of this writing). These are the only tests run for the conformance tests, and in the regression tests they can be run by clicking the "Run tests" button. For the regression tests, you can also enter your own tests manually in the box provided. In any event, the test input is a snippet of HTML, which must have a selection marked in it. There are three ways to mark a selection's start or end:
- Square brackets mark a selection inside a text node, like
<b>foo[bar]baz</b>for a selection whose start and end nodes are in the text nodefoobarbaz, with start offset 3 and end offset 6. Do not use square brackets where there's no text node:<b>[]</b>is bad,<b>{}</b>is correct. - Curly braces mark a selection inside an element, like
<b>{foobarbaz</b>}for a selection whose start node is the element<b>, whose start offset is 0, whose end node is the root of the editable region, and whose end offset is 1. Do not use curly braces in the middle of a text node:foo{bar}bazis bad,foo[bar]bazis correct. - The
data-startanddata-endattributes mark a selection inside an element if a curly brace can't be put there in text/html. For instance,<table><tr>{<td>foo</td>}</tr></table>doesn't work because when the fragment is parsed, the curly braces end up outside the table. Instead, you have to do<table><tr data-start=0 data-end=1><td>foo</table>.
Every input must have exactly one start marker and one end marker, which
will be removed from the DOM before the test is run. You can mix and match
marker types, e.g., [foo}.
There is one special test type that behaves differently, "multitest". This allows running several tests in succession, which is needed at least for testing the effect of commands' state override or value override. The syntax is JSON, and looks like
[HTML input, [command name 1, command value 1], [command name 2, command value 2], . . .]
where all the variables are properly-quoted JSON strings. queryCommand*() are not run for multitests.
In all cases, prefixing the test string (or the first string in the test array, for arrays) with "!" has a special effect. The "!" will be stripped, and the test will be added to an array of bad tests. These tests will be omitted from the conformance tests. This is used to mark tests where the reference implementation is known to currently give bad results, either because of a bug in the reference implementation or a bug in the spec. Bad tests will still be run as development tests.
Commands that are expected to vary significantly based on the value of the
CSS styling flag are run twice. The first time runs
execCommand("styleWithCSS", false, "false") before every
command, and the second runs execCommand("styleWithCSS", false,
"true") before every command. All other commands other than multitests
run execCommand("styleWithCSS", false, "false") before every
command. The extra tests are not run as regression tests, in IE or Opera,
because they don't implement the styleWithCSS
command (but of course the conformance tests always all run).
The implementation is also used for an actual rich-text editor, but it's currently more of a toy than anything. Significant functionality is probably broken, especially outside of Gecko/WebKit. I might spend some more time getting it to work right, but it's certainly not going to be very useful on real-world sites, since there's no way any of this stuff will work in IE8.
Command development tests
The development tests are mostly useful for developing the spec itself, not for use by authors or browser implementers. They consist of a suite of fully automated tests plus a few separate suites of manual tests. The tests are:
The automated tests run the JavaScript implementation of the specification
on a particular input, then run the browser's implementation on the same input
for comparison. The results of running automated tests are placed in a table,
with rows marked as passing or failing based on whether the browser output is
"close enough" to the spec output. Since the tests are designed for debugging
the spec rather than actually testing conformance, minor variations are allowed
to avoid having browsers fail many tests for uninteresting reasons. Passes and
fails are based only on execCommand() output, not queryCommand*(): the latter is sanity-checked, and colored green
or red if it's known to be right or wrong on general principle, but spec and
browser output are not compared.
The tests will optionally store the specification's result for each test in
localStorage, and will raise an alert for any new test (no
stored output), any test whose spec output is different from the last run, and
any test whose spec output is otherwise clearly bad (e.g., producing a
non-serializable DOM). This is mostly useful for debugging and
regression-testing the spec itself, and is probably not interesting to anyone
other than me.
When a test runs, first the code sets up a contenteditable div with the
given contents and sets the selection as requested. Then it runs
queryCommandIndeterm(), queryCommandState(), and
queryCommandValue(), and their values are noted. Then it runs
execCommand(). Finally, it runs
queryCommandIndeterm(), queryCommandState(), and
queryCommandValue() again. Then it adds the output to the table.
The manual tests are much like the automated tests, with some key
differences. They only test one command each, with one input value (if
applicable). When a test is run, everything proceeds as in the automated case,
but instead of running execCommand() for the browser tests, the
user is asked to hit the appropriate key (backspace, delete, enter, etc.).
Thus when running the tests for the first time, the user has to hit a key
repeatedly, perhaps a few hundred times. The browser's result is then cached
in localStorage so no manual intervention is required on
subsequent runs except for newly-added tests, but the cached entries can be
cleared if necessary.
The development tests have been tested and largely work in the latest versions (at the time of this writing) of IE, Firefox, Chrome, and Opera. Since the implementation of the spec is in JavaScript, it's vulnerable to bugs in browsers' JavaScript implementations. I work around or warn about some of these, but not all. The most correct results will probably be in Firefox or Chrome: both IE and Opera have serious known bugs that corrupt spec output for many tests. The tests are still useful for reviewing the browser output, but spec output in those browsers should be sanity-checked and compared against another browser's spec output in case of doubt.
Command conformance tests
The conformance tests operate more like one would expect from tests. Once generated, they consist of a single page, conformancetest/runtest.html, which runs all the tests and prints out a table of passes and fails. Like many other recent web standards suites, they use the testharness.js framework, and browser implementers should be able to make them part of their automated regression test frameworks.
For manual inspection, a version of the conformance tests is also available that runs only some of the tests at once: conformancetest/splitruntest.html. This runs only one group of tests at a time, which takes only a few seconds instead of a minute or more. This makes debugging particular tests much faster. In all other respects, it should behave identically to runtest.html.
Unlike the development tests, the conformance tests don't run the JavaScript implementation as part of the test. Instead, the tests' expected values are generated by a separate page, conformancetest/gentest.html. That page will output the expected values for all tests in a format to be copied to conformancetest/data.js, where it will be used by runtest.html.
This separation has a few benefits. First of all, it means the conformance
tests take a long time to generate, but run much faster than the
development tests: on the order of one minute instead of five or more.
(Browser implementations of execCommand() are currently much faster
than the spec's JS reference implementation, it seems.) Second of all, it
means that all browsers are running against the same expected results. Third
of all, the fact that all expected results are saved in a file allows much more
systematic regression testing of the spec and the reference implementation.
Changes in expected results will be recorded in the spec's version history and
can be matched up to changes in the reference implementation or the spec,
instead of being stored transiently in the spec editor's localStorage
and then lost.
There are a couple of disadvantages as well. For one thing, new tests can't
easily be added live, so the conformance tests aren't useful for experimenting
with how implementations work. For another thing, the tests' expected results
can only be generated all at once (not per-command), which takes minutes. A
third issue is that they provide no useful feedback at all about user actions
such as hitting Enter: they tell you what the insertParagraph command does in the browser, but not
whether it matches up to any user action. Commands like the insertText command just fail all tests in most browsers.
Thus they don't replace the manual development tests at all. (Manual
conformance tests will eventually be added.)
As might be expected, browsers don't generate exactly the same expected
results from the tests. Clearly incorrect expected results (like a DOM that
doesn't round-trip through text/html) are automatically rejected, with a
printed warning, but some discrepancies remain. At the time of this writing,
Firefox 8.0a2 and Chrome 15 dev generate identical results, except that Firefox
omits one test (due to incorrect
serialization of <xmp>) and Chrome gets one test wrong (due to a
style resolution
bug). Thus I generate the tests right now in Firefox, since all its
generated tests are at least correct. IE9 and Opera 11.50 don't yet generate
or run the tests usefully at all in this initial version, but this will be
remedied soon.
Event firing is currently tested in a totally separate file, event.html. In the long term, this will probably be merged into runtest.html so that it's tested more thoroughly.
Issues
This section is not normative.
This specification is mostly feature-complete. It's more or less fully implemented in JavaScript, and has been tested on a fairly significant amount of artificial input. It has not been tested on real-world sites that use execCommand(), and has not been thoroughly reviewed by anyone other than me. It should be considered mostly stable and awaiting implementater review and feedback.
Significant known issues that I need feedback on, or otherwise am not planning to fix just yet:
- Need to make CSS terminology more precise, about setting/unsetting CSS properties. The intent is to modify the style attribute, CSSOM-style. Suggestions appreciated on how I should spec this.
- I use resolved value instead of computed or used or anything like that, just because that's what my test implementation uses (via getComputedStyle). This is not necessarily the best actual choice: if it should be something else, please tell me.
I haven't paid much attention to performance. The algorithms here aren't performance-critical in most cases, but I might have accidentally included some algorithms that are too slow anyway on large pages. Generally I haven't worried about throwing nodes away and recreating them multiple times or things like that, as long as it produces the correct result.
If it would be useful to implementers for me to spend time and spec complexity on avoiding some of the masses of useless operations that are currently required, please say so. All intermediate DOM states are black-box detectable via mutation events or whatever their replacement will be, so implementers theoretically can't optimize most of this stuff too much themselves, but in practice I doubt anyone will rely on the intermediate DOM states much.
brs are a nightmare. I have tons of hacks all over the place which are totally wrong, mostly to account for the fact that sometimesbrs do nothing and we need to treat that case magically. I don't know what a good way is to fix this. At this point I've mostly gotten the evil concentrated in the definitions "collapsed line break", "extraneous line break", and "collapsed block prop", but there's lots of other special-case handling scattered about. Feedback appreciated. How do browsers handle this?- The CSS styling flag is an issue. Currently authors are forced to turn
it entirely on or entirely off. If it's on, it produces stuff like
<span style=font-weight:bold>instead of<b>, while if it's off, it produces stuff like<font color=red>instead of<span style=color:red>. The issue is that authors might want a mix, like making the markup as concise as possible while still conforming, and they can't do that. Changing the flag on a per-command basis doesn't help because of things like the "restore the values" algorithm, which might create several different types of style at once and has to use the same styling flag for all of them. This was discussed back in March in this thread, along with a number of other things, but at that time I hadn't written commands that change multiple styles at once, so it seemed feasible to ask authors to switch styleWithCSS on or off on a per-command basis. - I haven't defined the "undo" or "redo" commands yet. They look very complicated to define precisely, and other people are working on them right now.
A variety of other issues are also noted in the text, formatted like this. Feedback would be appreciated on all of them.
Things that would be useful to address for the future but aren't important to fix right now are in comments prefixed with "TODO".
Selections
Every document with a non-null
defaultView
has a unique Selection object associated with it.
Selection objects are known as
selections. Each selection is
associated with a single range, which may be null and is initially null.
This one selection must be shared by all the content of the document
(though not by nested documents), including any editing hosts in the
document. Editing hosts that are not
inside a document cannot have a selection.
A document's selection is a singleton object associated with that
document, so it gets replaced with a new object when Document.open() is called.
The user agent should allow the user to change the active document's selection. If the user makes any modification to a selection, the user agent must create a new range with suitable start and end and associate the selection with this new range (not modify the existing range). The user agent must not allow the user to set a selection's range to null if it was not already null.
Once a selection is associated with a given range, it must continue to be associated with that same range until this specification requires otherwise.
For instance, if the DOM changes in a way that changes the
range's boundary points, or a script modifies the boundary points of
the range, the same range object must continue to be associated with
the selection. However, if the user changes the selection or a script
calls addRange(), the selection
must be associated with a new range object, as required elsewhere in this
specification.
If the selection's range is not null and is collapsed, then
the caret position must be at that range's boundary point. When the
selection is not empty, this specification does not define the caret
position; user agents should follow platform conventions in deciding whether
the caret is at the start of the selection, the end of the selection,
or somewhere else.
Each selection has a direction, either forwards or backwards. If the user creates a selection by indicating first one boundary point of the range and then the other (such as by clicking on one point and dragging to another), and the first indicated boundary point is after the second, then the corresponding selection must initially be backwards. Otherwise, it must be forwards (including if the user didn't create the selection, created it by selecting an entire part of the page using a keyboard shortcut, etc.).
Wouldn't it make more sense if addRange()/removeRange() reset direction?
Selections also have an anchor and a focus. If the selection's range is null, its anchor and focus are both null. If the selection's range is not null and its direction is forwards, its anchor is the range's start, and its focus is the end. Otherwise, its focus is the start and its anchor is the end.
interface Selection {
readonly attribute Node? anchorNode;
readonly attribute unsigned long anchorOffset;
readonly attribute Node? focusNode;
readonly attribute unsigned long focusOffset;
readonly attribute boolean isCollapsed;
void collapse(Node node, unsigned long offset);
void collapseToStart();
void collapseToEnd();
void extend(Node node, unsigned long offset);
void selectAllChildren(Node node);
void deleteFromDocument();
readonly attribute unsigned long rangeCount;
Range getRangeAt(unsigned long index);
void addRange(Range range);
void removeRange(Range range);
void removeAllRanges();
stringifier;
};
Originally, the Selection interface was a Netscape feature. The original implementation was carried on into Gecko (Firefox), and the feature was later implemented independently by other browser engines. The Netscape implementation always allowed multiple ranges in a single selection, for instance so the user could select a column of a table. However, multi-range selections proved to be an unpleasant corner case that web developers didn't know about and even Gecko developers rarely handled correctly. Other browser engines never implemented the feature, and clamped selections to a single range in various incompatible fashions.
This specification follows non-Gecko engines in restricting selections to at
most one range, but the API was still originally designed for selections with
arbitrary numbers of ranges. This explains oddities like the coexistence of
removeRange() and removeAllRanges(), and a
getRangeAt() method that takes an integer argument that must always be
zero.
All of the members of the Selection interface are defined in
terms of operations on the range object (if any) represented by the object.
These operations can raise exceptions, as defined for the Range interface; this can therefore result in the
members of the Selection interface raising exceptions as well, in
addition to any explicitly called out below.
What happens if you try to put a selection in some node that's not part of the selection's document? Assuming it works, how is it presented to the user?
What does getSelection().getRangeAt(0).detach() do?
- selection .
anchorNode -
Returns the element that contains the start of the selection.
Returns null if there's no selection.
- selection .
anchorOffset -
Returns the offset of the start of the selection relative to the element that contains the start of the selection.
Returns 0 if there's no selection.
- selection .
focusNode -
Returns the element that contains the end of the selection.
Returns null if there's no selection.
- selection .
focusOffset -
Returns the offset of the end of the selection relative to the element that contains the end of the selection.
Returns 0 if there's no selection.
The anchorNode
attribute must return the context object's anchor's node,
or null if the anchor is null.
The anchorOffset
attribute must return the context object's anchor's
offset, or 0 if the anchor is null.
The focusNode
attribute must return the context object's focus's node, or
null if the focus is null.
The focusOffset
attribute must return the context object's focus's
offset, or 0 if the focus is null.
- collapsed = selection .
isCollapsed() -
Returns true if there's no selection or if the selection is empty. Otherwise, returns false.
- selection .
collapse(node, offset) -
Replaces the selection with a collapsed one at the given position.
Throws an
IndexSizeErrorexception if offset is negative or longer than node's length. - selection .
collapseToStart() -
Replaces the selection with an empty one at the position of the start of the current selection.
Throws an
InvalidStateErrorexception if there is no selection. - selection .
collapseToEnd() -
Replaces the selection with an empty one at the position of the end of the current selection.
Throws an
InvalidStateErrorexception if there is no selection. - selection .
extend(node, offset) -
Changes the focus while leaving the anchor in place.
Throws an
InvalidStateErrorif there's no selection, anInvalidNodeTypeErrorif node is a doctype, and anIndexSizeErrorexception if offset is negative or longer than node's length.
The isCollapsed
attribute must return true if the anchor and focus
are the same (including if both are null). Otherwise it must return false.
The collapse(node,
offset) method must create a new range,
set both its start and end to
(node, offset), and set the context object's range
to the newly-created range.
The collapseToStart() method
must throw an InvalidStateError exception if the context object's
range is null. Otherwise, it must create a new range object,
set both its start and end to the
context object's range's start, and then set the
context object's range to the newly-created range.
The collapseToEnd() method
must throw an InvalidStateError exception if the context object's
range is null. Otherwise, it must create a new range object,
set both its start and end to the
context object's range's end, and then set the
context object's range to the newly-created range.
The extend(node,
offset) method must run these steps:
-
If the context object's range is null, throw an
InvalidStateErrorexception and abort these steps. - Let anchor and focus be the context object's anchor and focus, and let new focus be the boundary point (node, offset).
-
Let new range be a new range.
-
If node's root is not the same as the context object's range's root, set new range's start and end to (node, offset).
- Otherwise, if anchor is before or equal to new focus, set new range's start to anchor, then set its end to new focus.
- Otherwise, set new range's start to new focus, then set its end to anchor.
- Set the context object's range to new range.
- If new focus is before anchor, set the context object's direction to backwards. Otherwise, set it to forwards.
- selection .
selectAllChildren(node) -
Replaces the selection with one that contains all the contents of the given element.
- selection .
deleteFromDocument() -
Deletes the selection.
The selectAllChildren(node)
method must run the following steps:
-
Let range be a new range.
- Set range's start to (node, 0).
- Set range's end to (node, number of node's children).
- Set the context object's range to range.
- Set the context object's direction to forwards.
The deleteFromDocument()
method must do nothing if the context object's range is null, and
otherwise must invoke the deleteContents() method on the
context object's range.
Should we replace the range rather than mutating it here? This is currently the only Selection method that actually mutates an existing range in place.
- selection .
rangeCount -
Returns the number of ranges in the selection (either 0 or 1).
- selection .
getRangeAt(index) -
Returns the selection's range, if index is 0.
Throws an
IndexSizeErrorexception if index is not 0, or if there is no range in the selection. - selection .
addRange(range) -
Adds the given range to the selection.
- selection .
removeRange(range) -
Unselects everyting, if range is in the selection. (Use
removeAllRanges()instead.) - selection .
removeAllRanges() -
Unselects everything.
The rangeCount
attribute must return 0 if the context object's range is null, otherwise
1.
The getRangeAt(index)
method must throw an IndexSizeError exception if index is not
0, or if the context object's range is null. Otherwise, it must return
a reference to (not a copy of) the context object's range. (Thus
subsequent calls must return the same object if nothing has removed the
context object's range in the meantime.)
The addRange(range)
method must set the context object's range to a reference to (not a copy
of) range. Since range is added by reference, subsequent
calls to getRangeAt(0) must return
the same object, and any changes that a script makes to range after
it is added must be reflected in the selection, until something else
removes or replaces the context object's range.
The removeRange(range)
method must set the context object's range to null if its range is
currently range, otherwise do nothing.
Do we check for object equality here or just equality of boundary points?
The removeAllRanges() method
must set the context object's range to null and its direction to
forwards.
The stringifier must . . .
Complicated. The Selection stringifier is magical like innerText. See W3C bug 10583.
This specification extends several interfaces to provide entry points to the interfaces defined in this specification.
- window .
getSelection()- document .
getSelection() - document .
-
Returns the
Selectionobject for the window, which stringifies to the text of the current selection.
partial interface Document { Selection getSelection(); };
The getSelection()
method on the Document interface must return
null if the context object's defaultView is null, and the
context object's selection otherwise.
partial interface Window { Selection getSelection(); };
The getSelection()
method on the Window interface must return
the same thing as calling
getSelection() on the document
returned by the context object's
document property.
Commands
Properties of commands
This specification defines a number of commands, identified by ASCII case-insensitive strings. Each command can have several pieces of data associated with it:
- Action: What the command does when executed via
execCommand(). Every command defined in this specification has an action defined for it in the relevant section. For example, theboldcommand's action generally makes the current selection bold, or removes bold if the selection is already bold. An editing toolbar might provide buttons that execute the action for a command if clicked, or a script might run an action without user interaction to achieve some particular effect. Actions return either true or false, which can affect the return value ofexecCommand(). - Indeterminate: A boolean value returned by
queryCommandIndeterm(), depending on the current state of the document. Generally, a command that has a state defined will be indeterminate if the state is true for part but not all of the current selection, and a command that has a value defined will be indeterminate if different parts of the selection have different values. An editing toolbar might display a button or control in a special way if the command is indeterminate, like showing a "bold" button as partially depressed, or leaving a font size selector blank instead of showing the font size of the current selection. As a rule, a command can only be indeterminate if its state is false, supposing it has a state. - State: A boolean value returned by
queryCommandState(), depending on the current state of the document. The state of a command is true if it is already in effect, in some sense specific to the command. Most commands that have a state defined will take opposite actions depending on whether the state is true or false, such as making the selection bold if the state is false and removing bold if the state is true. Others will just have no effect if the state is true, like thejustifyCentercommand. Still others will have the same effect regardless, like thestyleWithCsscommand. An editing toolbar might display a button or control differently depending on the state and indeterminacy of the command. - Value: A string returned by
queryCommandValue(), depending on the current state of the document. A command usually has a value instead of a state if the property it modifies can take more than two different values, like theforeColorcommand. If the command is indeterminate, its value is generally based on the start of the selection. Otherwise, in most cases the value holds true for the entire selection, but see thejustifyCentercommand and its three companions for an exception. An editing toolbar might display the value of a command as selected in a drop-down or filled in in a text box, if the command isn't indeterminate. - Relevant CSS property: This is defined for certain inline formatting commands, and is used in algorithms specific to those commands. It is an implementation detail, and is not exposed to authors. If a command does not have a relevant CSS property specified, it defaults to null.
Supported commands
Some commands will be supported in a
given user agent, and some will not. All commands
defined in this specification must be supported, except optionally
the copy command, the cut command, and/or the paste
command. Additional
vendor-specific commands can also be
supported, but implementers must prefix any
vendor-specific command names with a vendor-specific string (e.g.,
"ms", "moz", "webkit", "opera").
A command that does absolutely nothing in a particular user
agent, such that execCommand() never has any effect and
queryCommandEnabled() and queryCommandIndeterm() and
queryCommandState() and queryCommandValue() each
return the same value all the time, must not be supported.
In a particular user agent, every command must be consistently either supported or not. Specifically, a user agent must not permit one page to see the same command sometimes supported and sometimes not over the course of the same browsing session, unless the user agent has been upgraded or reconfigured in the middle of a session. However, user agents may treat the same command as supported for some pages and not others, e.g., if the command is only supported for certain origins for security reasons.
Authors can tell whether a command is supported
using queryCommandSupported().
Enabled commands
At any given time, a supported command can be either
enabled or not. Authors can tell whether a command is
currently enabled using queryCommandEnabled(). Commands that are not enabled do nothing, as
described in the definitions of the various methods that invoke commands.
Among commands defined in this specification,
those listed in Miscellaneous commands are
always enabled, except for the cut
command and the paste command. The
other commands defined here are enabled
if the active range is not null, its start node is either
editable or an editing host, its end node is
either editable or an editing host, and there is some
editing host that is an inclusive ancestor of both its
start node and its end node.
Methods to query and execute commands
We fire events as requested in bug 13118. This is a new feature does not currently match any browser. If you are implementing this, please make sure to file any feedback as bugs. The spec is not finalized yet and can still be easily changed.
[Constructor(DOMString type, optional EditingBeforeInputEventInit eventInitDict)] interface EditingBeforeInputEvent : Event { readonly attribute DOMString command; readonly attribute DOMString value; }; dictionary EditingBeforeInputEventInit : EventInit { DOMString command; DOMString value; }; [Constructor(DOMString type, optional EditingInputEventInit eventInitDict)] interface EditingInputEvent : Event { readonly attribute DOMString command; readonly attribute DOMString value; }; dictionary EditingInputEventInit : EventInit { DOMString command; DOMString value; };
We have two different interfaces because we might want to add additional members to the input event but not the beforeinput event, such as a list of nodes that were affected.
When an EditingBeforeInputEvent object is created, the
command and
value
attributes must both be initialized to the empty string, unless otherwise
specified.
When an EditingInputEvent object is created, the
command and
value attributes must
both be initialized to the empty string, unless otherwise specified.
When the execCommand(command,
show UI, value) method on the HTMLDocument interface is invoked, the user agent
must run the following steps:
- If only one argument was provided, let show UI be false.
- If only one or two arguments were provided, let value be the empty string.
-
If command is not in the Miscellaneous commands section:
We don't fire events for copy/cut/paste/undo/redo/selectAll because they should all have their own events. We don't fire events for styleWithCSS/useCSS because it's not obvious where to fire them, or why anyone would want them. We don't fire events for unsupported commands, because then if they became supported and were classified with the miscellaneous events, we'd have to stop firing events for consistency's sake.
- Let affected editing host be the editing host
that is an inclusive ancestor of the active range's
start node and end node, and is not the ancestor of any
editing host that is an inclusive ancestor of the
active range's start node and end node.
Such an editing host must exist, because otherwise the command would not be enabled.
- Dispatch an event at affected editing host that uses
the
EditingBeforeInputEventinterface. The event'stypeattribute must be initialized to "beforeinput"; itsisTrusted,bubbles, andcancelableattributes must be initialized to true; itscommandattribute must be initialized to command; and itsvalueattribute must be initialized to value. - If the value returned by the previous step is false, return false.
- If command is not enabled, return false.
We have to check again whether the command is enabled, because the beforeinput handler might have done something annoying like getSelection().removeAllRanges().
- Let affected editing host be the editing host
that is an inclusive ancestor of the active range's
start node and end node, and is not the ancestor of any
editing host that is an inclusive ancestor of the
active range's start node and end node.
This new affected editing host is what we'll fire the input event at in a couple of lines. We want to compute it beforehand just to be safe: bugs in the command action might remove the selection or something bad like that, and we don't want to have to handle it later. We recompute it after the beforeinput event is handled so that if the handler moves the selection to some other editing host, the input event will be fired at the editing host that was actually affected.
- Let affected editing host be the editing host
that is an inclusive ancestor of the active range's
start node and end node, and is not the ancestor of any
editing host that is an inclusive ancestor of the
active range's start node and end node.
- Take the action for command, passing value to the instructions as an argument.
- If the previous step returned false, return false.
- If command is not in the
Miscellaneous commands section, then
dispatch an event at affected editing host that uses the
EditingInputEventinterface. The event'stypeattribute must be initialized to "input"; itsisTrustedandbubblesattributes must be initialized to true; itscommandattribute must be initialized to command; and itsvalueattribute must be initialized to value. - Return true.
When the queryCommandEnabled(command)
method on the HTMLDocument interface is
invoked, the user agent must run the following steps:
When the queryCommandIndeterm(command)
method on the HTMLDocument interface is
invoked, the user agent must run the following steps:
-
If command is not supported or has no indeterminacy, return false.
- Return true if command is indeterminate, otherwise false.
When the queryCommandState(command)
method on the HTMLDocument interface is
invoked, the user agent must run the following steps:
- If the state override for command is set, return it.
- Return true if command's state is true, otherwise false.
When the queryCommandSupported(command)
method on the HTMLDocument interface is
invoked, the user agent must return true if command is
supported, and false otherwise.
When the queryCommandValue(command)
method on the HTMLDocument interface is
invoked, the user agent must run the following steps:
-
If command is not supported or has no value, return the empty string.
-
If command is "fontSize" and its value override is set, convert the value override to an integer number of pixels and return the legacy font size for the result.
- If the value override for command is set, return it.
- Return command's value.
All of these methods must treat their command argument ASCII case-insensitively.
The methods in this section have mostly been designed so that the following
invariants hold after execCommand() is called, assuming it
didn't throw an exception:
queryCommandIndeterm()will return false (or throw an exception).queryCommandState()will return the opposite of what it did beforeexecCommand()was called (or throw an exception).queryCommandValue()will return something equivalent to the value passed toexecCommand()(or throw an exception). "Equivalent" here needs to be construed broadly in some cases, such asfontSize.
The first two points do not always hold for strikethrough
or underline, because it can be impossible to unset
text-decoration in CSS. Also, by design, the state of insertOrderedList and insertUnorderedList might
be true both before and after calling, because they only remove one level of
indentation. unlink should set the value to null. And
finally, the state of the various justify commands should
always be true after calling, and the value should always be the appropriate
string ("center", "justify", "left", or "right"). Any other deviations from
these invariants are bugs in the specification.
Common definitions
An HTML element is an Element whose namespace is the
HTML namespace.
A prohibited paragraph child name is "address", "article", "aside", "blockquote", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", or "xmp".
A prohibited paragraph child is an HTML element whose local name is a prohibited paragraph child name.
A block node is either an Element whose "display" property
does not have resolved value "inline" or "inline-block" or "inline-table" or
"none", or a document, or a DocumentFragment.
An inline node is a node that is not a block node.
An editing host is a node that is either an HTML
element with a contenteditable attribute set to the true
state, or the HTML element child of a document whose designMode is enabled.
Something is editable if it is a node; it is not an
editing host; it does not have a contenteditable attribute set to the false
state; its parent is an editing host or editable;
and either it is an HTML element, or it is an svg or math
element, or it is not an Element and its parent is an HTML
element.
An editable node cannot be a document or
DocumentFragment, its parent cannot be null, and it must descend from
either an Element or a document.
The editing host of node is null if node is neither editable nor an editing host; node itself, if node is an editing host; or the nearest ancestor of node that is an editing host, if node is editable.
Two nodes are in the same editing host if the editing host of the first is non-null and the same as the editing host of the second.
Barring bugs, the algorithms here will not alter the attributes of a non-editable element; will not remove a non-editable node from its parent (except to immediately give it a new parent in the same editing host); and will not add, remove, or reorder children of a node unless it is either editable or an editing host. An editing host is never editable, so authors are assured that editing commands will only modify the editing host's contents and not the editing host itself.
A collapsed line break is a br that begins a line box which
has nothing else in it, and therefore has zero height.
Is this a good definition at all? I mean things like <p>foo<br></p>, or the second one in <p>foo<br><br></p>. The way I test it is by adding a text node after it containing a zwsp; if that changes the offsetHeight of its nearest non-inline ancestor, I deem it collapsed. But what if it happens to be display: none right now, for instance? Or its ancestor has a fixed height? Would it be better to use some DOM-based definition?
An is a br that has no visual effect,
in that removing it from the DOM would not change layout, except that a br
that is the sole child of an li is not extraneous.
Also possibly a bad definition. Again, I test by just removing it and seeing what happens. (Actually, setting display: none, so that it doesn't mess up ranges.)
A whitespace node is either a Text node whose data is
the empty string; or a Text node whose data consists only of one or
more tabs (0x0009), line feeds (0x000A), carriage returns (0x000D), and/or
spaces (0x0020), and whose parent is an Element whose resolved value for
"white-space" is "normal" or "nowrap"; or a Text node whose data
consists only of one or more tabs (0x0009), carriage returns (0x000D), and/or
spaces (0x0020), and whose parent is an Element whose resolved value for
"white-space" is "pre-line".
node is a collapsed whitespace node if the following algorithm returns true:
This definition is also bad. It's a crude attempt to emulate CSS2.1 16.6.1, but leaving out a ton of the subtleties. I actually don't want the exact CSS definitions, because those depend on things like where lines are broken, but I'm not sure this definition is right anyway. E.g., what about a pre-line text node consisting of a single line break that's at the end of a block? That collapses, same idea as an extraneous line break. We could also worry about nodes containing only zwsp or such if we wanted, or display: none, or . . .
- If node is not a whitespace node, return false.
- If node's
datais the empty string, return true. - Let ancestor be node's parent.
- If ancestor is null, return true.
- If the "display" property of some ancestor of node has resolved value "none", return true.
- While ancestor is not a block node and its parent is not null, set ancestor to its parent.
-
Let reference be node.
- While reference is a descendant of ancestor:
- Let reference be the node before it in tree order.
- If reference is a block node or a
br, return true. - If reference is a
Textnode that is not a whitespace node, or is animg, break from this loop.
Let reference be node.
- While reference is a descendant of ancestor:
- Let reference be the node after it in tree order, or null if there is no such node.
- If reference is a block node or a
br, return true. - If reference is a
Textnode that is not a whitespace node, or is animg, break from this loop.
- Return false.
Something is visible if it is a node that either is a
block node, or a Text node that is not a collapsed
whitespace node, or an img, or a br that is not an
extraneous line break, or any node with a visible
descendant; excluding any node with an inclusive ancestor
Element whose "display" property has resolved value "none".
Something is invisible if it is a node that is not visible.
A collapsed block prop is either a collapsed line
break that is not an extraneous line break, or an
Element that is an inline node and whose children are all
either invisible or collapsed
block props and that has at least one child that is a
collapsed block prop.
A collapsed block prop is something like the <br> in <p><br></p>, or the <br> and <span> in <p><span><br></span></p>. These are necessary to
stop the block from having zero height when it has no other contents, but serve
no purpose and should be removed once the block has other contents that stop it
from collapsing.
The active range is the range of the selection given by
calling getSelection() on the context object. (Thus the active
range may be null.)
Each HTMLDocument has a boolean CSS styling flag associated
with it, which must initially be false. (The styleWithCSS command can be used to modify or query it, by
means of the execCommand() and queryCommandState()
methods.)
Each HTMLDocument is associated with a string known as the
default single-line container name, which must initially be "p".
(The defaultParagraphSeparator command can be
used to modify or query it, by means of the execCommand() and
queryCommandValue() methods.)
For some commands, each HTMLDocument must
have a boolean state override and/or a string value
override. These do not change the command's
state or value, but change the way some algorithms
behave, as specified in those algorithms' definitions. Initially, both must be
unset for every command. Whenever the number of ranges in the
selection changes to something different, and whenever a boundary point
of the range at a given index in the selection changes to something
different, the state override and value override must
be unset for every command. The value override for
the backColor command must be the same as the
value override for the hiliteColor
command, such that setting one sets the other to the same thing and
unsetting one unsets the other.
The primary purpose of state and value overrides is that if the
user runs a command like bold
with a collapsed selection, then types something without moving the cursor,
they expect it to have the given style (bold or such). Thus the commands like
bold set state and value
overrides, and insertText checks for them and applies them to the
newly-inserted text. Other commands like delete also interact with overrides.
When
document.open() is
called and a document's singleton objects are all replaced by new instances
of those objects, editing state associated with that document (including the
CSS styling flag, default single-line container name,
and any state overrides or
value overrides) must be reset.
Of course, any action that replaces a document object entirely, such as reloading the page, will also reset any editing state associated with the document.
When this specification refers to a method or attribute that is defined in a specification, the user agent must treat the method or attribute as defined by that specification. In particular, if a script has overridden a standard property with a custom one, the user agent must only use the overridden property when a script refers to it, and must continue to use the specification-defined behavior when this specification refers to it.
When a list or set of nodes is assigned to a variable without specifying the order, they must be initially in tree order, if they share a root. (If they don't share a root, the order will be specified.) When the user agent is instructed to run particular steps for each member of a list, it must do so sequentially in the list's order.
Common algorithms
Assorted common algorithms
To move a node to a new location, preserving ranges, remove the node from its original parent (if any), then insert it in the new location. In doing so, follow these rules instead of those defined by the insert and remove algorithms:
Many of the algorithms in this specification move nodes around in
the DOM. The normal rules for range mutation require that any range endpoints
inside those nodes are moved to the node's parent as soon as the node is moved,
which would corrupt the selection. For instance, if the user selects the text
"foo" and then bolds it, first we produce <b></b>foo, then <b>foo</b>. When
we move the "foo" text node into its new parent, we have to do so "preserving
ranges", so that the text "foo" is still selected.
- Let node be the moved node, old parent and old index be the old parent (which may be null) and index, and new parent and new index be the new parent and index.
-
If a boundary point's node is the same as or a descendant of node, leave it unchanged, so it moves to the new location.
- If a boundary point's node is new parent and its offset is greater than new index, add one to its offset.
- If a boundary point's node is old parent and its offset is old index or old index + 1, set its node to new parent and add new index − old index to its offset.
- If a boundary point's node is old parent and its offset is greater than old index + 1, subtract one from its offset.
To set the tag name of an Element element to
new name:
This is needed because the DOM doesn't allow any way of changing an existing element's name. Sometimes we want to, e.g., convert a markup element to a span. In that case we invoke this algorithm to create a new element, move it to the right place, copy attributes from the old element, move the old element's children, and remove the old element.
- If element is an HTML element with local name equal to new name, return element.
- If element's parent is null, return element.
- Let replacement element be the result of calling
createElement(new name)on theownerDocumentof element. - Insert replacement element into element's parent immediately before element.
- Copy all attributes of element to replacement element, in order.
- While element has children, append the first child of element as the last child of replacement element, preserving ranges.
- Remove element from its parent.
- Return replacement element.
To a node node:
<br> sometimes has no effect in CSS, such
as in the markup foo<br><p>bar</p>. In such cases
we like to remove the extra markup to keep things tidy.
- Let ref be the
previousSiblingof node. - If ref is null, abort these steps.
- While ref has children, set ref to its
lastChild. - While ref is invisible but not an extraneous line break, and ref does not equal node's parent, set ref to the node before it in tree order.
- If ref is an editable extraneous line break, remove it from its parent.
To a node node:
- Let ref be node.
- While ref has children, set ref to its
lastChild. - While ref is invisible but not an extraneous line break, and ref does not equal node, set ref to the node before it in tree order.
- If ref is an editable extraneous line break:
To a node, first remove extraneous line breaks before it, then remove extraneous line breaks at the end of it.
Wrapping a list of nodes
To wrap a list node list of consecutive sibling nodes, run the following algorithm. In addition to node list, the algorithm accepts two inputs: an algorithm sibling criteria that accepts a node as input and outputs a boolean, and an algorithm new parent instructions that accepts nothing as input and outputs a node or null. If not provided, sibling criteria returns false and new parent instructions returns null.
This algorithm basically does two things. First, it looks at the
previous and next siblings of the nodes in node list. If running
sibling criteria on one or both of the siblings returns true, the
nodes in node list are moved into the sibling(s). Otherwise,
new parent instructions is run, and the result is used to wrap
node list. For instance, to wrap node list in a <b>, one might invoke this algorithm with sibling
criteria returning true only for <b> elements and
new parent instructions creating and returning a new <b> element.
-
If every member of node list is invisible, and none is a
br, return null and abort these steps. - If node list's first member's parent is null, return null and abort these steps.
-
If node list's last member is an inline node that's not a
br, and node list's last member'snextSiblingis abr, append thatbrto node list. -
While node list's first member's
previousSiblingis invisible, prepend it to node list. - While node list's last member's
nextSiblingis invisible, append it to node list. - If the
previousSiblingof the first member of node list is editable and running sibling criteria on it returns true, let new parent be thepreviousSiblingof the first member of node list. - Otherwise, if the
nextSiblingof the last member of node list is editable and running sibling criteria on it returns true, let new parent be thenextSiblingof the last member of node list. - Otherwise, run new parent instructions, and let new parent be the result.
-
If new parent is null, abort these steps and return null.
If new parent's parent is null:
- Insert new parent into the parent of the first member of node list immediately before the first member of node list.
-
If any range has a boundary point with node equal to the parent of new parent and offset equal to the index of new parent, add one to that boundary point's offset.
- Let original parent be the parent of the first member of node list.
- If new parent is before the first member of node
list in tree order:
- If new parent is not an inline node, but the
last visible child of new parent and the first
visible member of node list are both inline nodes, and the last child of new
parent is not a
br, callcreateElement("br")on theownerDocumentof new parent and append the result as the last child of new parent. - For each node in node list, append node as the last child of new parent, preserving ranges.
- If new parent is not an inline node, but the
last visible child of new parent and the first
visible member of node list are both inline nodes, and the last child of new
parent is not a
- Otherwise:
- If new parent is not an inline node, but the
first visible child of new parent and the last
visible member of node list are both inline nodes, and the last member of node
list is not a
br, callcreateElement("br")on theownerDocumentof new parent and insert the result as the first child of new parent. - For each node in node list, in reverse order, insert node as the first child of new parent, preserving ranges.
- If new parent is not an inline node, but the
first visible child of new parent and the last
visible member of node list are both inline nodes, and the last member of node
list is not a
-
If original parent is editable and has no children, remove it from its parent.
-
If new parent's
nextSiblingis editable and running sibling criteria on it returns true:- If new parent is not an inline node, but
new parent's last child and new parent's
nextSibling's first child are both inline nodes, and new parent's last child is not abr, callcreateElement("br")on theownerDocumentof new parent and append the result as the last child of new parent. - While new parent's
nextSiblinghas children, append its first child as the last child of new parent, preserving ranges. - Remove new parent's
nextSiblingfrom its parent.
- If new parent is not an inline node, but
new parent's last child and new parent's
- Remove extraneous line breaks from new parent.
- Return new parent.
Allowed children
A name of an element with inline contents is "a", "abbr", "b", "bdi", "bdo", "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small", "span", "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike", "xmp", "big", "blink", "font", "marquee", "nobr", or "tt".
An element with inline contents is an HTML element whose local name is a name of an element with inline contents.
A node or string child is an allowed child of a node or string parent if the following algorithm returns true:
Often we move around nodes, and sometimes this can result in
unreasonable things like two <p>'s nested inside one
another. This algorithm checks for DOMs we never want to have, so that other
algorithms can avoid creating them or fix them if they do happen. The
fix disallowed ancestors algorithm is one frequently-invoked
caller of this algorithm.
- If parent is "colgroup", "table", "tbody", "tfoot", "thead",
"tr", or an HTML element with local name equal to one of
those, and child is a
Textnode whosedatadoes not consist solely of space characters, return false. -
If parent is "script", "style", "plaintext", or "xmp", or an HTML element with local name equal to one of those, and child is not a
Textnode, return false. - If child is a document,
DocumentFragment, orDocumentType, return false. - If child is an HTML element, set child to the local name of child.
- If child is not a string, return true.
- If parent is an HTML element:
-
If child is "a", and parent or some ancestor of parent is an
a, return false. -
If child is a prohibited paragraph child name and parent or some ancestor of parent is an element with inline contents, return false.
-
If child is "h1", "h2", "h3", "h4", "h5", or "h6", and parent or some ancestor of parent is an HTML element with local name "h1", "h2", "h3", "h4", "h5", or "h6", return false.
-
Let parent be the local name of parent.
-
- If parent is an
ElementorDocumentFragment, return true. - If parent is not a string, return false.
-
If parent is on the left-hand side of an entry on the following list, then return true if child is listed on the right-hand side of that entry, and false otherwise.
- colgroup: col
- table: caption, col, colgroup, tbody, td, tfoot, th, thead, tr
- tbody, tfoot, thead: td, th, tr
- tr: td, th
- dl: dt, dd
- dir, ol, ul: dir, li, ol, ul
- hgroup: h1, h2, h3, h4, h5, h6
- If child is "body", "caption", "col", "colgroup", "frame", "frameset", "head", "html", "tbody", "td", "tfoot", "th", "thead", or "tr", return false.
-
If child is "dd" or "dt" and parent is not "dl", return false.
- If child is "li" and parent is not "ol" or "ul", return false.
- If parent is on the left-hand side of an entry on the
following list and child is listed on the right-hand side of that
entry, return false.
- a: a
- dd, dt: dd, dt
- h1, h2, h3, h4, h5, h6: h1, h2, h3, h4, h5, h6
- li: li
- nobr: nobr
- All names of an element with inline contents: all prohibited paragraph child names
- td, th: caption, col, colgroup, tbody, td, tfoot, th, thead, tr
- Return true.
Inline formatting commands
Inline formatting command definitions
A node node is effectively contained in a
range range if range is not collapsed, and
at least one of the following holds:
A modifiable element is a b, em, i, s, span,
strike, strong, sub, sup, or u element with no attributes
except possibly style; or a font element with no attributes except
possibly style, color, face, and/or size; or an
a element with no attributes except possibly style and/or href.
A simple modifiable element is an HTML element for which at least one of the following holds:
- It is an
a,b,em,font,i,s,span,strike,strong,sub,sup, oruelement with no attributes. - It is an
a,b,em,font,i,s,span,strike,strong,sub,sup, oruelement with exactly one attribute, which isstyle, which sets no CSS properties (including invalid or unrecognized properties). - It is an
aelement with exactly one attribute, which ishref. - It is a
fontelement with exactly one attribute, which is eithercolor,face, orsize. - It is a
borstrongelement with exactly one attribute, which isstyle, and thestyleattribute sets exactly one CSS property (including invalid or unrecognized properties), which is "font-weight". - It is an
ioremelement with exactly one attribute, which isstyle, and thestyleattribute sets exactly one CSS property (including invalid or unrecognized properties), which is "font-style". - It is an
a,font, orspanelement with exactly one attribute, which isstyle, and thestyleattribute sets exactly one CSS property (including invalid or unrecognized properties), and that property is not "text-decoration". - It is an
a,font,s,span,strike, oruelement with exactly one attribute, which isstyle, and thestyleattribute sets exactly one CSS property (including invalid or unrecognized properties), which is "text-decoration", which is set to "line-through" or "underline" or "overline" or "none".
Conceptually, a simple modifiable element is a modifiable element
which specifies a value for at most one command. As the names imply, inline
formatting commands will try not to modify anything other than modifiable
elements. For instance, <dfn> normally creates italics,
but it's not modifiable, so running the italic
command will not remove it: it will nest <span
style="font-style: normal"> inside.
A formattable node is an editable
visible node that is either a Text node, an img, or a
br.
Two quantities are equivalent values for a command if either both are null, or both are strings and they're equal and the command does not define any equivalent values, or both are strings and the command defines equivalent values and they match the definition.
Two quantities are loosely equivalent values for a
command if either they are equivalent values for the
command, or if the command is the fontSize command; one of the quantities is one of
"x-small", "small", "medium", "large", "x-large", "xx-large", or "xxx-large";
and the other quantity is the resolved value of "font-size" on a font element
whose size attribute has the corresponding value set ("1" through "7"
respectively).
Loose equivalence needs to be used when comparing effective command values to other values, while regular equivalence is used in other cases. The effective command value for fontSize is converted to pixels, so comparing it to a specified value literally would produce false negatives. But a specified value in pixels is actually different from a specified value like "small" or "x-large", because there is no precise mapping from such keywords to pixels.
If a command has inline command activated values defined but nothing else defines when it is indeterminate, it is indeterminate if among formattable nodes effectively contained in the active range, there is at least one whose effective command value is one of the given values and at least one whose effective command value is not one of the given values.
If a command has inline command activated values defined, its state is true if either no formattable node is effectively contained in the active range, and the active range's start node's effective command value is one of the given values; or if there is at least one formattable node effectively contained in the active range, and all of them have an effective command value equal to one of the given values.
If a command is a standard inline value command, it is indeterminate if among formattable nodes that are effectively contained in the active range, there are two that have distinct effective command values. Its value is the effective command value of the first formattable node that is effectively contained in the active range; or if there is no such node, the effective command value of the active range's start node; or if that is null, the empty string.
The notions of inline command activated values and standard inline value commands are mostly just shorthand to avoid repeating the same boilerplate half a dozen times.
Assorted inline formatting command algorithms
The effective command value of a node node for a given command is returned by the following algorithm, which will return either a string or null:
This is logically somewhat like CSS computed or resolved values,
and in fact for most commands it's identical to CSS resolved values (see the
end of the algorithm). We need a separate concept for some commands where we
can't rely on CSS for some reason: createLink and unlink aren't CSS-related at
all, backColor and hiliteColor need special treatment because background-color
isn't an inherited property, subscript and superscript rely on <sub>/<sup> instead of CSS
vertical-align, and strikethrough and underline don't map to unique CSS
properties.
- If neither node nor its parent is an
Element, return null. - If node is not an
Element, return the effective command value of its parent for command. - If command is "createLink" or "unlink":
- If command is "backColor" or "hiliteColor":
- While the resolved value of "background-color" on node is
any fully transparent value, and node's parent is an
Element, set node to its parent. -
Return the resolved value of "background-color" for node.
- While the resolved value of "background-color" on node is
any fully transparent value, and node's parent is an
- If command is "subscript" or "superscript":
- Let affected by subscript and affected by superscript be two boolean variables, both initially false.
- While node is an inline node:
- If affected by subscript and affected by superscript are both true, return the string "mixed".
- If affected by subscript is true, return "subscript".
- If affected by superscript is true, return "superscript".
- Return null.
- If command is "strikethrough", and the "text-decoration" property of node or any of its ancestors has resolved value containing "line-through", return "line-through". Otherwise, return null.
- If command is "underline", and the "text-decoration" property of node or any of its ancestors has resolved value containing "underline", return "underline". Otherwise, return null.
- Return the resolved value for node of the relevant CSS property for command.
The specified command value of an Element element
for a given command is returned by the following algorithm, which
will return either a string or null:
This is logically somewhat like CSS inline style. In addition to
the caveats for effective command value, we also treat elements like <b> and <font> as having the same meaning
as <span>s with inline style set, because they're
logically pretty much the same and can in fact be produced by the same command
depending on the CSS styling flag.
- If command is "backColor" or "hiliteColor" and the
Element's display property does not have resolved value "inline", return null. - If command is "createLink" or "unlink":
- If command is "subscript" or "superscript":
- If command is "strikethrough", and element has a
styleattribute set, and that attribute sets "text-decoration":- If element's
styleattribute sets "text-decoration" to a value containing "line-through", return "line-through". - Return null.
- If element's
- If command is "strikethrough" and element is an
sorstrikeelement, return "line-through". - If command is "underline", and element has a
styleattribute set, and that attribute sets "text-decoration":- If element's
styleattribute sets "text-decoration" to a value containing "underline", return "underline". - Return null.
- If element's
- If command is "underline" and element is a
uelement, return "underline". - Let property be the relevant CSS property for command.
- If property is null, return null.
- If element has a
styleattribute set, and that attribute has the effect of setting property, return the value that it sets property to. - If element is a
fontelement that has an attribute whose effect is to create a presentational hint for property, return the value that the hint sets property to. (For asizeof 7, this will be the non-CSS value "xxx-large".) - If element is in the following list, and property is equal to the CSS property name listed for it, return the string listed for it.
- Return null.
To record the values of a list of nodes node list:
When we move nodes around, we often change their parents. If
their parents had any styles applied, this will make the nodes' styles change
too, which often isn't what we want. For instance, if something is wrapped in
<blockquote style="color: red">, and a script runs
the outdent command on it, the blockquote will
be removed and the style will go along with it. Recording the values of its
children first, then restoring them afterward, will ensure the nodes don't
change color when outdented.
- Let values be a list of (node, command, specified command value) triples, initially empty.
-
For each node in node list, for each command in the list "subscript", "bold", "fontName", "fontSize", "foreColor", "hiliteColor", "italic", "strikethrough", and "underline" in that order:
- Let ancestor equal node.
- If ancestor is not an
Element, set it to its parent. - While ancestor is an
Elementand its specified command value for command is null, set it to its parent. - If ancestor is an
Element, add (node, command, ancestor's specified command value for command) to values. Otherwise add (node, command, null) to values.
- Return values.
To restore the values specified by a list values returned by the record the values algorithm:
- For each (node, command, value) triple
in values:
- Let ancestor equal node.
- If ancestor is not an
Element, set it to its parent. - While ancestor is an
Elementand its specified command value for command is null, set it to its parent. - If value is null and ancestor is an
Element, push down values on node for command, with new value null. - Otherwise, if ancestor is an
Elementand its specified command value for command is not equivalent to value, or if ancestor is not anElementand value is not null, force the value of command to value on node.
Clearing an element's value
To clear the value of an Element element:
The idea is to remove any specified command value that the element might have for the command. This might involve changing its attributes, setting its tag name, or removing it entirely while leaving its children in place. The key caller is set the selection's value, which clears the values of everything in the selection before doing anything else to keep the markup tidy.
- Let command be the current command.
- If element is not editable, return the empty list.
-
If element's specified command value for command is null, return the empty list.
- If element is a simple modifiable element:
- Let children be the children of element.
- For each child in children, insert child into element's parent immediately before element, preserving ranges.
- Remove element from its parent.
- Return children.
- If command is "strikethrough", and element has a
styleattribute that sets "text-decoration" to some value containing "line-through", delete "line-through" from the value. - If command is "underline", and element has a
styleattribute that sets "text-decoration" to some value containing "underline", delete "underline" from the value. - If the relevant CSS property for command is not null, unset that property of element.
- If element is a
fontelement: - If element is an
aelement and command is "createLink" or "unlink", unset thehrefproperty of element. -
If element's specified command value for command is null, return the empty list.
- Set the tag name of element to "span", and return the one-node list consisting of the result.
Pushing down values
To push down values to a node node, given a new value new value:
The idea here is that if an undesired value is being propagated from an ancestor, we remove that style from the ancestor and re-apply it to all the descendants other than node. This way we don't have to have nested styles, which is usually more cluttered (although not always).
- Let command be the current command.
- If the effective command value of command is loosely equivalent to new value on node, abort this algorithm.
- Let current ancestor be node's parent.
- Let ancestor list be a list of nodes, initially empty.
- While current ancestor is an editable
Elementand the effective command value of command is not loosely equivalent to new value on it, append current ancestor to ancestor list, then set current ancestor to its parent. - If ancestor list is empty, abort this algorithm.
- Let propagated value be the specified command value of command on the last member of ancestor list.
-
If propagated value is null and is not equal to new value, abort this algorithm.
-
If the effective command value of command is not loosely equivalent to new value on the parent of the last member of ancestor list, and new value is not null, abort this algorithm.
- While ancestor list is not empty:
- Let current ancestor be the last member of ancestor list.
- Remove the last member from ancestor list.
- If the specified command value of current ancestor for command is not null, set propagated value to that value.
- Let children be the children of current ancestor.
- If the specified command value of current ancestor for command is not null, clear the value of current ancestor.
- For every child in children:
- If child is node, continue with the next child.
-
If child is an
Elementwhose specified command value for command is neither null nor equivalent to propagated value, continue with the next child. - If child is the last member of ancestor list, continue with the next child.
- Force the value of child, with command as in this algorithm and new value equal to propagated value.
Forcing the value of a node
To force the value of a node node to new value:
This algorithm checks if the node has the desired value, and if not, it wraps the node (or, if that's not possible, its descendants) in a simple modifiable element. After forcing the value, descendants might still have a different value.
- Let command be the current command.
- If node's parent is null, abort this algorithm.
- If new value is null, abort this algorithm.
- If node is an allowed child of "span":
-
Reorder modifiable descendants of node's
previousSibling. - Reorder modifiable descendants of node's
nextSibling. -
Wrap the one-node list consisting of node, with sibling criteria returning true for a simple modifiable element whose specified command value is equivalent to new value and whose effective command value is loosely equivalent to new value and false otherwise, and with new parent instructions returning null.
-
-
If node is invisible, abort this algorithm.
- If the effective command value of command is loosely equivalent to new value on node, abort this algorithm.
- If node is not an allowed child of "span":
- Let children be all children of node,
omitting any that are
Elements whose specified command value for command is neither null nor equivalent to new value. -
Force the value of each node in children, with command and new value as in this invocation of the algorithm.
- Abort this algorithm.
- Let children be all children of node,
omitting any that are
- If the effective command value of command is loosely equivalent to new value on node, abort this algorithm.
- Let new parent be null.
- If the CSS styling flag is false:
- If command is "bold" and new value is
"bold", let new parent be the result of calling
createElement("b")on theownerDocumentof node. - If command is "italic" and new value is
"italic", let new parent be the result of calling
createElement("i")on theownerDocumentof node. -
If command is "strikethrough" and new value is "line-through", let new parent be the result of calling
createElement("s")on theownerDocumentof node. - If command is "underline" and new value is
"underline", let new parent be the result of calling
createElement("u")on theownerDocumentof node. -
If command is "foreColor", and new value is fully opaque with red, green, and blue components in the range 0 to 255:
- Let new parent be the result of calling
createElement("font")on theownerDocumentof node. - Set the
colorattribute of new parent to the result of applying the rules for serializing simple color values to new value (interpreted as a simple color).
- Let new parent be the result of calling
- If command is "fontName", let new parent be
the result of calling
createElement("font")on theownerDocumentof node, then set thefaceattribute of new parent to new value.
- If command is "bold" and new value is
"bold", let new parent be the result of calling
- If command is "createLink" or "unlink":
- Let new parent be the result of calling
createElement("a")on theownerDocumentof node. - Set the
hrefattribute of new parent to new value. -
Let ancestor be node's parent.
- While ancestor is not null:
-
If ancestor is an
a, set the tag name of ancestor to "span", and let ancestor be the result. - Set ancestor to its parent.
-
- Let new parent be the result of calling
-
If command is "fontSize"; and new value is one of "x-small", "small", "medium", "large", "x-large", "xx-large", or "xxx-large"; and either the CSS styling flag is false, or new value is "xxx-large": let new parent be the result of calling
createElement("font")on theownerDocumentof node, then set thesizeattribute of new parent to the number from the following table based on new value:- x-small: 1
- small: 2
- normal: 3
- large: 4
- x-large: 5
- xx-large: 6
- xxx-large: 7
-
If command is "subscript" or "superscript" and new value is "subscript", let new parent be the result of calling
createElement("sub")on theownerDocumentof node. - If command is "subscript" or "superscript" and new
value is "superscript", let new parent be the result of
calling
createElement("sup")on theownerDocumentof node. - If new parent is null, let new parent be the result
of calling
createElement("span")on theownerDocumentof node. -
Insert new parent in node's parent before node.
- If the effective command value of command for
new parent is not loosely equivalent to new value,
and the relevant CSS property for command is not
null, set that CSS property of new parent to new value
(if the new value would be valid).
Need to be explicit. I think "if the new value would be valid" means "if the new value isn't xxx-large for font-size", need to double-check.
- If command is "strikethrough", and new value is "line-through", and the effective command value of "strikethrough" for new parent is not "line-through", set the "text-decoration" property of new parent to "line-through".
- If command is "underline", and new value is "underline", and the effective command value of "underline" for new parent is not "underline", set the "text-decoration" property of new parent to "underline".
- Append node to new parent as its last child, preserving ranges.
- If node is an
Elementand the effective command value of command for node is not loosely equivalent to new value:- Insert node into the parent of new parent before new parent, preserving ranges.
- Remove new parent from its parent.
- Let children be all children of node,
omitting any that are
Elements whose specified command value for command is neither null nor equivalent to new value. - Force the value of each node in children, with command and new value as in this invocation of the algorithm.
To reorder modifiable descendants of a node node, given a command command and a value new value:
- Let candidate equal node.
- While candidate is a modifiable element, and candidate has exactly one child, and that child is also a modifiable element, and candidate is not a simple modifiable element or candidate's specified command value for command is not equivalent to new value, set candidate to its child.
- If candidate is node, or is not a simple modifiable element, or its specified command value is not equivalent to new value, or its effective command value is not loosely equivalent to new value, abort these steps.
- While candidate has children, insert the first child of candidate into candidate's parent immediately before candidate, preserving ranges.
-
Insert candidate into node's parent immediately after node.
- Append the node as the last child of candidate, preserving ranges.
Setting the selection's value
To set the selection's value to new value:
The effect of this algorithm is to ensure that all nodes effectively contained in the selection have the value requested, producing the simplest markup possible to achieve that effect. It's inspired by the approach WebKit takes. The only places where the algorithm should fail are when there's an !important CSS rule that conflicts with the requested style (which we don't try to override because we assume it's !important for a reason), or when it's literally impossible to succeed (such as when a text-decoration or link URL is propagated from a non-editable ancestor). Any other failures are bugs.
First, if a node has a specified command value for the command,
we unset it (clear its value). This step
also removes simple modifiable
elements entirely, and replaces elements like b or font with
spans if they aren't simple modifiable elements. This will be sufficient
if the desired value is inherited from an ancestor, or if it's the default
(like font-style: normal) and no conflicting value is inherited from an
ancestor. Even if clearing values doesn't actually fix the style of the node
we're dealing with, we do it anyway to simplify the generated markup.
If clearing values didn't work, and it looks like an ancestor has a specified command value that we're inheriting, we push the value down from that ancestor. Thus if we're unbolding the letter "r" in
we get
If we didn't push down values, the final step (forcing values) would instead give us
which is much longer and uglier. We take care not to disturb the style or semantics of anything but the node we're dealing with.
We'll only push down values if some ancestor actually has the value we want, so we can inherit it. Otherwise, it will just create useless markup.
Finally, if neither of the above strategies worked, we have to add new markup to get the desired value (forcing the value). First we try just sticking it into its previous or next sibling, if that's a simple modifiable element (so it won't add any styles or semantics we don't want). Otherwise, we create a new simple modifiable element and wrap it in that. It's common that a previous sibling is the simple modifiable element we want, because often we'll set the value of several consecutive siblings in succession. In that case, the element created for the first can be reused for the later ones.
This last step works a bit differently if the node isn't an allowed child of "span". In that case, wrapping it in a simple modifiable element would make the document less conforming than it already was, or would cause other problems. Instead, we recursively force the value of its children. The recursion will terminate when we hit a node that's an allowed child of "span", or when there are no further descendants. (In the latter case, there are no descendants that are text nodes or such, so we don't really need to style anything.)
After all this, the node is guaranteed to have the value we want, barring bugs in the algorithm or the two exceptions noted earlier (!important style rules, and impossible cases). We then re-run the algorithm on each child recursively. Typically this means just clearing the value of each descendant, because it should then inherit the value we just set on its ancestor. In the unusual case that a descendant's value is wrong even after we clear its value, such as because of a non-inline style rule (like trying to unbold a heading), we'll repeat the above steps to ensure that the value really gets set as desired.
- Let command be the current command.
-
If there is no formattable node effectively contained in the active range:
- If command has inline command activated values, set the state override to true if new value is among them and false if it's not.
- If command is "subscript", unset the state override for "superscript".
- If command is "superscript", unset the state override for "subscript".
- If new value is null, unset the value override (if any).
- Otherwise, if command is "createLink" or it has a value specified, set the value override to new value.
- Abort these steps.
-
If the active range's start node is an editable
Textnode, and its start offset is neither zero nor its start node's length, callsplitText()on the active range's start node, with argument equal to the active range's start offset. Then set the active range's start node to the result, and its start offset to zero. - If the active range's end node is an
editable
Textnode, and its end offset is neither zero nor its end node's length, callsplitText()on the active range's end node, with argument equal to the active range's end offset. - Let element list be all editable
Elements effectively contained in the active range. - For each element in element list, clear the value of element.
-
Let node list be all editable nodes effectively contained in the active range.
-
For each node in node list:
- Push down values on node.
-
If node is an allowed child of "span", force the value of node.
The backColor command
For historical reasons, backColor and hiliteColor behave identically.
- If value is not a valid CSS color, prepend "#" to it.
- If value is still not a valid CSS color, or if it is currentColor, return false.
- Set the selection's value to value.
- Return true.
Relevant CSS property: "background-color"
Equivalent values: Either both strings are valid CSS colors and have the same red, green, blue, and alpha components, or neither string is a valid CSS color.
The bold command
Action: If queryCommandState("bold") returns true,
set the selection's value to "normal". Otherwise set the
selection's value to "bold". Either way, return true.
Inline command activated values: "bold", "600", "700", "800", or "900"
Relevant CSS property: "font-weight"
Equivalent values: Either the two strings are equal, or one is "bold" and the other is "700", or one is "normal" and the other is "400".
The createLink command
-
If value is the empty string, return false.
-
For each editable
aelement that has anhrefattribute and is an ancestor of some node effectively contained in the active range, set thataelement'shrefattribute to value. - Set the selection's value to value.
- Return true.
The fontName command
Action: Set the selection's value to value, then return true.
Relevant CSS property: "font-family"
The fontSize command
- Strip leading and trailing whitespace from value.
- If value is not a valid floating point number, and would not be a valid floating point number if a single leading "+" character were stripped, return false.
- If the first character of value is "+", delete the character and let mode be "relative-plus".
- Otherwise, if the first character of value is "-", delete the character and let mode be "relative-minus".
- Otherwise, let mode be "absolute".
- Apply the rules for parsing non-negative integers to value, and let number be the result.
- If mode is "relative-plus", add three to number.
- If mode is "relative-minus", negate number, then add three to it.
- If number is less than one, let number equal 1.
- If number is greater than seven, let number equal 7.
- Set value to the string here corresponding to
number:
- 1: x-small
- 2: small
- 3: medium
- 4: large
- 5: x-large
- 6: xx-large
- 7: xxx-large
- Set the selection's value to value.
- Return true.
Indeterminate: True if among formattable nodes that are effectively contained in the active range, there are two that have distinct effective command values. Otherwise false.
- If the active range is null, return the empty string.
-
Let pixel size be the effective command value of the first formattable node that is effectively contained in the active range, or if there is no such node, the effective command value of the active range's start node, in either case interpreted as a number of pixels.
- Return the legacy font size for pixel size.
Relevant CSS property: "font-size"
The legacy font size for an integer pixel size is returned by the following algorithm:
- Let returned size be 1.
- While returned size is less than 7:
- Let lower bound be the resolved value of "font-size" in pixels
of a
fontelement whosesizeattribute is set to returned size. - Let upper bound be the resolved value of "font-size" in pixels
of a
fontelement whosesizeattribute is set to one plus returned size. - Let average be the average of upper bound and lower bound.
- If pixel size is less than average, return the one-code unit string consisting of the digit returned size.
- Add one to returned size.
- Let lower bound be the resolved value of "font-size" in pixels
of a
- Return "7".
The foreColor command
-
If value is not a valid CSS color, prepend "#" to it.
-
If value is still not a valid CSS color, or if it is currentColor, return false.
- Set the selection's value to value.
- Return true.
Relevant CSS property: "color"
Equivalent values: Either both strings are valid CSS colors and have the same red, green, blue, and alpha components, or neither string is a valid CSS color.
The hiliteColor command
For historical reasons, backColor and hiliteColor behave identically.
- If value is not a valid CSS color, prepend "#" to it.
-
If value is still not a valid CSS color, or if it is currentColor, return false.
- Set the selection's value to value.
- Return true.
Relevant CSS property: "background-color"
Equivalent values: Either both strings are valid CSS colors and have the same red, green, blue, and alpha components, or neither string is a valid CSS color.
The italic command
Action: If queryCommandState("italic") returns true,
set the selection's value to "normal". Otherwise set the
selection's value to "italic". Either way, return true.
Inline command activated values: "italic" or "oblique"
Relevant CSS property: "font-style"
The removeFormat command
A removeFormat candidate is an editable HTML element with local name "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", or "var".
- Let elements to remove be a list of every removeFormat candidate effectively contained in the active range.
- For each element in elements to remove:
- While element has children, insert the first child of element into the parent of element immediately before element, preserving ranges.
- Remove element from its parent.
-
If the active range's start node is an editable
Textnode, and its start offset is neither zero nor its start node's length, callsplitText()on the active range's start node, with argument equal to the active range's start offset. Then set the active range's start node to the result, and its start offset to zero. - If the active range's end node is an
editable
Textnode, and its end offset is neither zero nor its end node's length, callsplitText()on the active range's end node, with argument equal to the active range's end offset. - Let node list consist of all editable nodes effectively contained in the active range.
-
For each node in node list, while node's parent is a removeFormat candidate in the same editing host as node, split the parent of the one-node list consisting of node.
-
For each of the entries in the following list, in the given order, set the selection's value to null, with command as given.
- subscript
- bold
- fontName
- fontSize
- foreColor
- hiliteColor
- italic
- strikethrough
- underline
- Return true.
The strikethrough command
Action: If queryCommandState("strikethrough") returns
true, set the selection's value to null. Otherwise set the
selection's value to "line-through". Either way, return true.
Inline command activated values: "line-through"
The subscript command
- Call
queryCommandState("subscript"), and let state be the result. - Set the selection's value to null.
- If state is false, set the selection's value to "subscript".
- Return true.
Indeterminate: True if either among formattable nodes that are effectively contained in the active range, there is at least one with effective command value "subscript" and at least one with some other effective command value; or if there is some formattable node effectively contained in the active range with effective command value "mixed". Otherwise false.
Inline command activated values: "subscript"
The superscript command
- Call
queryCommandState("superscript"), and let state be the result. - Set the selection's value to null.
- If state is false, set the selection's value to "superscript".
- Return true.
Indeterminate: True if either among formattable nodes that are effectively contained in the active range, there is at least one with effective command value "superscript" and at least one with some other effective command value; or if there is some formattable node effectively contained in the active range with effective command value "mixed". Otherwise false.
Inline command activated values: "superscript"
The underline command
Action: If queryCommandState("underline") returns true,
set the selection's value to null. Otherwise set the
selection's value to "underline". Either way, return true.
Inline command activated values: "underline"
The unlink command
- Let hyperlinks be a list of every
aelement that has anhrefattribute and is contained in the active range or is an ancestor of one of its boundary points. - Clear the value of each member of hyperlinks.
- Return true.
Block formatting commands
Block formatting command definitions
An indentation element is either a blockquote, or a div
that has a style attribute that sets "margin" or some subproperty of it.
A simple indentation element is an indentation element that has no attributes except possibly
- a
styleattribute that sets no properties other than "margin", "border", "padding", or subproperties of those; and/or - a
dirattribute.
The notions of indentation element and simple indentation element parallel those of modifiable element and simple modifiable element.
A non-list single-line container is an HTML element with local name "address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", or "xmp".
A single-line container is either a non-list single-line container, or an HTML element with local name "li", "dt", or "dd".
The block node of a node node is either a block node or null, as returned by the following algorithm:
- While node is an inline node, set node to its parent.
- Return node.
If a command preserves overrides, then before taking
its action, the user agent must record current
overrides. After taking the action, if the active
range is collapsed, it must restore states and
values from the recorded list.
All block commands preserve overrides except the
insertText command, which treats overrides specially.
Assorted block formatting command algorithms
To fix disallowed ancestors of node:
We often run this algorithm after we move a node someplace, just in case it wound up somewhere it's not supposed to be. This avoids things like unserializable DOMs, blocks nested inside inlines, etc.
- If node is not editable, abort these steps.
-
If node is not an allowed child of any of its ancestors in the same editing host:
- If node is a
ddordt, wrap the one-node list consisting of node, with sibling criteria returning true for anydlwith no attributes and false otherwise, and new parent instructions returning the result of callingcreateElement("dl")on the context object. Then abort these steps. -
If "p" is not an allowed child of the editing host of node, abort these steps.
- If node is not a prohibited paragraph child, abort these steps.
- Set the tag name of node to the default single-line container name, and let node be the result.
-
Fix disallowed ancestors of node.
- Let children be node's children.
- For each child in children, if child
is a prohibited paragraph child:
- Record the values of the one-node list consisting of child, and let values be the result.
- Split the parent of the one-node list consisting of child.
- Restore the values from values.
- Abort these steps.
- If node is a
- Record the values of the one-node list consisting of node, and let values be the result.
- While node is not an allowed child of its parent, split the parent of the one-node list consisting of node.
- Restore the values from values.
To normalize sublists in a node item:
- If item is not an
lior it is not editable or its parent is not editable, abort these steps. - Let new item be null.
- While item has an
olorulchild:- Let child be the last child of item.
- If child is an
olorul, or new item is null and child is aTextnode whosedataconsists of zero of more space characters:- Set new item to null.
- Insert child into the parent of item immediately following item, preserving ranges.
- Otherwise:
- If new item is null, let new item be the
result of calling
createElement("li")on theownerDocumentof item, then insert new item into the parent of item immediately after item. - Insert child into new item as its first child, preserving ranges.
- If new item is null, let new item be the
result of calling
The selection's list state is returned by the following algorithm:
This is just a helper to tell the state and indeterminacy of
the insertOrderedList command and the
insertUnorderedList command:
| ol indeterm | ol state | ul indeterm | ul state | |
|---|---|---|---|---|
| ol | false | true | false | false |
| ul | false | false | false | true |
| mixed | true | false | true | false |
| mixed ol | true | false | false | false |
| mixed ul | false | false | true | false |
| none | false | false | false | false |
- If the active range is null, return "none".
- Block-extend the active range, and let new range be the result.
- Let node list be a list of nodes, initially empty.
- For each node contained in new range, append
node to node list if the last member of node
list (if any) is not an ancestor of node;
node is editable; node is not an
indentation element; and node is either an
olorul, or the child of anolorul, or an allowed child of "li". - If node list is empty, return "none".
-
If every member of node list is either an
olor the child of anolor the child of anlichild of anol, and none is aulor an ancestor of aul, return "ol". -
If every member of node list is either a
ulor the child of aulor the child of anlichild of aul, and none is anolor an ancestor of anol, return "ul". - If some member of node list is either an
olor the child or ancestor of anolor the child of anlichild of anol, and some member of node list is either aulor the child or ancestor of aulor the child of anlichild of aul, return "mixed". - If some member of node list is either an
olor the child or ancestor of anolor the child of anlichild of anol, return "mixed ol". - If some member of node list is either a
ulor the child or ancestor of aulor the child of anlichild of aul, return "mixed ul". - Return "none".
The alignment value of a node node is returned by the following algorithm:
This is basically like the resolved value of text-align, but with two key differences. First, it only ever evaluates to center/justify/left/right, since that's the model that the justify commands work with. Second, it ignores inline elements, because text-align has no effect on them and their alignment is actually governed by their nearest block ancestor (if any).
- While node is neither null nor an
Element, or it is anElementbut its "display" property has resolved value "inline" or "none", set node to its parent. -
If node is not an
Element, return "left". - If node's "text-align" property has resolved value "start", return "left" if the directionality of node is "ltr", "right" if it is "rtl".
- If node's "text-align" property has resolved value "end", return "right" if the directionality of node is "ltr", "left" if it is "rtl".
- If node's "text-align" property has resolved value "center", "justify", "left", or "right", return that value.
- Return "left".
Sometimes one location corresponds to multiple distinct boundary
points. For instance, in the DOM <p>Hello</p>, a boundary point might
lie at the beginning of the text node or the beginning of the element node, but
these don't logically differ much and will appear the same to the user, so we
often want to treat them the same. The algorithms here allow navigating
through such equivalent boundary points, for when we want to make the selection
as inclusive or exclusive as possible. For deletion, we want to delete as few
nodes as possible, so we move the start node forward and the end node backward.
In other cases we might do the reverse, expanding the selection. In still
other cases we might want to move forward or backward to try getting to a text
node.
Given a boundary point (node, offset), the next equivalent point is either a boundary point or null, as returned by the following algorithm:
- If node's length is zero, return null.
- We don't want to move into or out of zero-length nodes,
because that would move us straight through them. For instance, if
{}<span></span>were equivalent to<span>{}</span>, it would also be equivalent to<span></span>{}. This produces very unexpected results for nodes like<br>. - If offset is node's length, and node's parent is not null, and node is an inline node, return (node's parent, 1 + node's index).
- For instance,
<span>foo[]</span>is equivalent to<span>foo{}</span>, which is equivalent to<span>foo</span>{}. However,<p>foo{}</p>is not equivalent to<p>foo</p>{}– the cursor might look like it's in a visibly different position. - If node has a child with index offset, and that child's length is not zero, and that child is an inline node, return (that child, 0).
- For instance,
{}<span>foo</span>is equivalent to<span>{}foo</span>, which is equivalent to<span>[]foo</span>. As noted before, though, we don't descend into empty nodes. And again,{}<p>foo</p>is different from<p>{}foo</p>. - Return null.
Given a boundary point (node, offset), the previous equivalent point is either a boundary point or null, as returned by the following algorithm:
- If node's length is zero, return null.
- If offset is 0, and node's parent is not null, and node is an inline node, return (node's parent, node's index).
- If node has a child with index offset − 1, and that child's length is not zero, and that child is an inline node, return (that child, that child's length).
- Return null.
The first equivalent point of a boundary point (node, offset) is returned by the following algorithm:
- While (node, offset)'s previous equivalent point is not null, set (node, offset) to its previous equivalent point.
- Return (node, offset).
The last equivalent point of a boundary point (node, offset) is returned by the following algorithm:
- While (node, offset)'s next equivalent point is not null, set (node, offset) to its next equivalent point.
- Return (node, offset).
Block-extending a range
A boundary point (node, offset) is a block
start point if either node's parent is null and
offset is zero; or node has a child with index
offset − 1, and that child is either a
visible block node or a visible br.
A boundary point (node, offset) is a block end point if either node's parent is null and offset is node's length; or node has a child with index offset, and that child is a visible block node.
A boundary point is a block boundary point if it is either a block start point or a block end point.
When a user agent is to block-extend a range range, it must run the following steps:
Generally, block commands work on any block that contains part of the selection, even if the selection doesn't include the whole block. This algorithm takes an input range, copies it, stretches out the copy to contain entire blocks, and returns the result. Then the caller will normally use it instead of the range it started with. For instance, if the cursor is collapsed in a text node inside a paragraph, this will generally return a range that includes the whole paragraph.
Two bits of magic worth noting. First, <br> counts as
a block delimiter here, since it looks the same as a block boundary (assuming
no margin etc.) and this is a visual API. We include the <br> as part of the line that precedes it. Second, if the
selection is inside an <li>, this will extend it to
include the whole <li>. This latter point is weird, and
I should re-examine it sometime, but it seems to work.
- Let start node, start offset, end node, and end offset be the start and end nodes and offsets of range.
- If some inclusive ancestor of start node is an
li, set start offset to the index of the last suchliin tree order, and set start node to thatli's parent. - If (start node, start offset) is not a block
start point, repeat the following steps:
- If start offset is zero, set it to start node's index, then set start node to its parent.
- Otherwise, subtract one from start offset.
- If (start node, start offset) is a block boundary point, break from this loop.
While start offset is zero and start node's parent is not null, set start offset to start node's index, then set start node to its parent.
- If some inclusive ancestor of end node is an
li, set end offset to one plus the index of the last suchliin tree order, and set end node to thatli's parent. - If (end node, end offset) is not a block end
point, repeat the following steps:
- If end offset is end node's length, set it to one plus end node's index, then set end node to its parent.
- Otherwise, add one to end offset.
- If (end node, end offset) is a block boundary point, break from this loop.
- While end offset is end node's length and end node's parent is not null, set end offset to one plus end node's index, then set end node to its parent.
- Let new range be a new range whose start and end nodes and offsets are start node, start offset, end node, and end offset.
- Return new range.
A node node follows a line break if the following algorithm returns true:
- Let offset be zero.
- While (node, offset) is not a block boundary point:
- Return true.
A node node precedes a line break if the following algorithm returns true:
- Let offset be node's length.
- While (node, offset) is not a block boundary point:
- Return true.
Recording and restoring overrides
To record current overrides:
- Let overrides be a list of (string, string or boolean) ordered pairs, initially empty.
-
If there is a value override for "createLink", add ("createLink", value override for "createLink") to overrides.
-
For each command in the list "bold", "italic", "strikethrough", "subscript", "superscript", "underline", in order: if there is a state override for command, add (command, command's state override) to overrides.
- For each command in the list "fontName", "fontSize", "foreColor", "hiliteColor", in order: if there is a value override for command, add (command, command's value override) to overrides.
- Return overrides.
To record current states and values:
- Let overrides be a list of (string, string or boolean) ordered pairs, initially empty.
- Let node be the first formattable node effectively contained in the active range, or null if there is none.
- If node is null, return overrides.
- Add ("createLink", node's effective command value for "createLink") to overrides.
-
For each command in the list "bold", "italic", "strikethrough", "subscript", "superscript", "underline", in order: if node's effective command value for command is one of its inline command activated values, add (command, true) to overrides, and otherwise add (command, false) to overrides.
- For each command in the list "fontName", "foreColor", "hiliteColor", in order: add (command, command's value) to overrides.
-
Add ("fontSize", node's effective command value for "fontSize") to overrides.
This is wrong: it will convert non-pixel sizes to pixel sizes. But I don't see any way to avoid it. Hopefully it won't come up too often. font-size is a real problem, because the mapping from specified value to computed value is lossy and not fully defined (e.g., how many px is "small"?).
- Return overrides.
To restore states and values specified by a list overrides returned by the record current overrides or record current states and values algorithm:
- Let node be the first formattable node effectively contained in the active range, or null if there is none.
- If node is not null, then for each (command,
override) pair in overrides, in order:
- If override is a boolean, and
queryCommandState(command)returns something different from override, take the action for command, with value equal to the empty string. - Otherwise, if override is a string, and command
is neither "createLink" nor "fontSize", and
queryCommandValue(command)returns something not equivalent to override, take the action for command, with value equal to override. -
Otherwise, if override is a string; and command is "createLink"; and either there is a value override for "createLink" that is not equal to override, or there is no value override for "createLink" and node's effective command value for "createLink" is not equal to override: take the action for "createLink", with value equal to override.
-
Otherwise, if override is a string; and command is "fontSize"; and either there is a value override for "fontSize" that is not equal to override, or there is no value override for "fontSize" and node's effective command value for "fontSize" is not loosely equivalent to override:
- Convert override to an integer number of pixels, and set override to the legacy font size for the result.
- Take the action for "fontSize", with value equal to override.
- Otherwise, continue this loop from the beginning.
-
Set node to the first formattable node effectively contained in the active range, if there is one.
- If override is a boolean, and
- Otherwise, for each (command, override) pair in
overrides, in order:
- If override is a boolean, set the state override for command to override.
- If override is a string, set the value override for command to override.
Deleting the selection
To delete the selection, given a block merging flag that defaults to true, a strip wrappers flag that defaults to true, and a string direction that defaults to "forward":
The idea behind this algorithm is self-explanatory, but the details wind up being remarkably complicated.
First, any editable nodes inside the selection will be deleted, and the
selection will be collapsed. By way of contrast, effectively
contained tries to expand the range to include as much as possible, so
<p>[foo]</p> contains the <p>. What we do here is contract
the range to include as little as possible, so {<p>foo</p>} contains
only foo and doesn't delete the paragraph.
After that, if the selection originally started and ended in different
blocks, and the block merging flag is true, the end block will get
merged into the start block. This is needed so if the user selects text on
several lines and deletes it, the text immediately that was before the
selection winds up on the same line as the text immediately after it. For
example, <p>fo[o</p><div>b]ar</div> becomes <p>fo[]ar</p>.
This procedure winds up being tricky, and takes up a large chunk of the logic.
Tables are a notable special case. If an entire table is contained in the range, it will be deleted. If it's anything less, only the contents of the cells will be deleted and the table structure will be left intact.
The strip wrappers flag controls what happens if the deletion
removes all the contents of an inline element. If wrappers are being stripped,
the empty inline element will be removed: this is usually what you want,
because the user can't position the selection inside it. But callers like
the insertText command that intend to
immediately insert new contents want to leave the wrappers, so the new contents
are wrapped by the same thing as the old.
Even if strip wrappers is true, the algorithm will set a state override and value override for any styles it winds up removing. This way, if the user deletes a wrapper that adds a style (or link for that matter), then types something, the new text will get the style from the old text.
- If the active range is null, abort these steps and do nothing.
- Canonicalize whitespace at the active range's start.
- Canonicalize whitespace at the active range's end.
- Let (start node, start offset) be the last equivalent point for the active range's start.
- Let (end node, end offset) be the first equivalent point for the active range's end.
- If (end node, end offset) is not after
(start node, start offset):
This is a selection like
<span>foo[</span></span>]bar</span>, where the boundary points are equivalent but not identical. We just collapse it and abort, since there's nothing to delete.- If direction is "forward", call
collapseToStart()on the context object's selection. - Otherwise, call
collapseToEnd()on the context object's selection. - Abort these steps.
- If direction is "forward", call
- If start node is a
Textnode and start offset is 0, set start offset to the index of start node, then set start node to its parent. - If end node is a
Textnode and end offset is its length, set end offset to one plus the index of end node, then set end node to its parent.The previous two steps are so that we won't leave empty text nodes anywhere.
- Call
collapse(start node, start offset)on the context object's selection. - Call
extend(end node, end offset)on the context object's selection. -
When we delete a selection that spans multiple blocks, we merge the end block's contents into the start block, like
<p>fo[o</p><pre>b]ar</pre> -> <p>fo[]ar</p>.
We figure out what the start and end blocks are before we start deleting anything.
- Let start block be the active range's start node.
- While start block's parent is in the same editing host and start block is an inline node, set start block to its parent.
-
If start block is neither a block node nor an editing host, or "span" is not an allowed child of start block, or start block is a
tdorth, set start block to null. - Let end block be the active range's end node.
- While end block's parent is in the same editing host and end block is an inline node, set end block to its parent.
- If end block is neither a block node nor an
editing host, or "span" is not an allowed child of
end block, or end block is a
tdorth, set end block to null. -
Later on we'll restore overrides. This ensures that if we delete inline formatting elements and the user then types something, the typed text will have the same style as before.
-
Record current states and values, and let overrides be the result.
-
Now we actually begin deleting things.
-
If start node and end node are the same, and start node is an editable
Textnode:- Call
deleteData(start offset, end offset − start offset)on start node. - Canonicalize whitespace at (start node, start offset), with fix collapsed space false.
- If direction is "forward", call
collapseToStart()on the context object's selection. - Otherwise, call
collapseToEnd()on the context object's selection. -
Restore states and values from overrides.
- Abort these steps.
- Call
- If start node is an editable
Textnode, calldeleteData()on it, with start offset as the first argument and (length of start node − start offset) as the second argument. - Let node list be a list of nodes, initially empty.
-
For each node contained in the active range, append node to node list if the last member of node list (if any) is not an ancestor of node; node is editable; and node is not a
thead,tbody,tfoot,tr,th, ortd. - For each node in node list:
- Let parent be the parent of node.
- Remove node from parent.
-
If the block node of parent has no visible children, and parent is editable or an editing host, call
createElement("br")on the context object and append the result as the last child of parent. -
If strip wrappers is true or parent is not an inclusive ancestor of start node, while parent is an editable inline node with length 0, let grandparent be the parent of parent, then remove parent from grandparent, then set parent to grandparent.
Even if strip wrappers is false, we still want to strip wrappers that aren't inclusive ancestors of start node. The idea of not stripping wrappers is that we're going to insert new content right afterward, like text or an image, but that new content will be inserted at the start node. Wrappers in other places still need to be removed, because they would otherwise remain empty.
- If end node is an editable
Textnode, calldeleteData(0, end offset)on it. - Canonicalize whitespace at the active range's start, with fix collapsed space false.
- Canonicalize whitespace at the active range's end, with fix collapsed space false.
-
Now we need to merge blocks. The simplest case is something like
<p>fo[o</p><p>bar</p><p>b]az</p> -> <p>fo</p>{}<p>az</p> -> <p>fo{}az</p>where neither block descends from the other. More complicated is something like
foo[<p>]bar</p> -> foo[]bar
or
<p>foo[</p>]bar -> <p>foo[]bar</p>
where one descends from the other.
- If block merging is false, or start block or
end block is null, or start block is not in the
same editing host as end block, or start block
and end block are the same:
- If direction is "forward", call
collapseToStart()on the context object's selection. - Otherwise, call
collapseToEnd()on the context object's selection. - Restore states and values from overrides.
- Abort these steps.
- If direction is "forward", call
-
If start block has one child, which is a collapsed block prop, remove its child from it.
-
If start block is an ancestor of end block:
- Let reference node be end block.
- While reference node is not a child of start block, set reference node to its parent.
- Call
collapse()on the context object's selection, with first argument start block and second argument the index of reference node. - If end block has no children:
- While end block is editable and is the only child of its parent and is not a child of start block, let parent equal end block, then remove end block from parent, then set end block to parent.
- If end block is editable and is not an
inline node, and its
previousSiblingandnextSiblingare both inline nodes, callcreateElement("br")on the context object and insert it into end block's parent immediately after end block. - If end block is editable, remove it from its parent.
- Restore states and values from overrides.
- Abort these steps.
- If end block's
firstChildis not an inline node, restore states and values from record, then abort these steps. - Let children be a list of nodes, initially empty.
- Append the first child of end block to children.
- While children's last member is not a
br, and children's last member'snextSiblingis an inline node, append children's last member'snextSiblingto children. - Record the values of children, and let values be the result.
- While children's first member's parent is not start block, split the parent of children.
- If children's first member's
previousSiblingis an editablebr, remove thatbrfrom its parent.
-
Otherwise, if start block is a descendant of end block:
- Call
collapse()on the context object's selection, with first argument start block and second argument start block's length. - Let reference node be start block.
- While reference node is not a child of end block, set reference node to its parent.
- If reference node's
nextSiblingis an inline node and start block'slastChildis abr, remove start block'slastChildfrom it. - Let nodes to move be a list of nodes, initially empty.
- If reference node's
nextSiblingis neither null nor a block node, append it to nodes to move. - While nodes to move is nonempty and its last member isn't a
brand its last member'snextSiblingis neither null nor a block node, append its last member'snextSiblingto nodes to move. - Record the values of nodes to move, and let values be the result.
- For each node in nodes to move, append node as the last child of start block, preserving ranges.
- Call
-
Otherwise:
- Call
collapse()on the context object's selection, with first argument start block and second argument start block's length. - If end block's
firstChildis an inline node and start block'slastChildis abr, remove start block'slastChildfrom it. - Record the values of end block's children, and let values be the result.
- While end block has children, append the first child of end block to start block, preserving ranges.
- While end block has no children, let parent be the parent of end block, then remove end block from parent, then set end block to parent.
- Call
We might have deleted the contents between two lists, in which case we should merge them. See bug 13976.
- Let ancestor be start block.
- While ancestor has an inclusive ancestor
olin the same editing host whosenextSiblingis also anolin the same editing host, or an inclusive ancestorulin the same editing host whosenextSiblingis also aulin the same editing host:- While ancestor and its
nextSiblingare not bothols in the same editing host, and are also not bothuls in the same editing host, set ancestor to its parent. - While ancestor's
nextSiblinghas children, append ancestor'snextSibling'sfirstChildas the last child of ancestor, preserving ranges. - Remove ancestor's
nextSiblingfrom its parent.
- While ancestor and its
- Restore the values from values.
- If start block has no children, call
createElement("br")on the context object and append the result as the last child of start block. - Remove extraneous line breaks at the end of start block.
- Restore states and values from overrides.
Splitting a node list's parent
To split the parent of a list node list of consecutive sibling nodes:
This algorithm breaks up the parent of node list. If they're the only children of their parent, the parent is removed entirely. If there are preceding or following siblings, the original parent is left intact as the parent of those siblings. If there are both preceding and following siblings, the original parent is left as the parent of the following siblings and a clone is used for the parent of the preceding siblings.
We make sure not to disrupt the appearance any more than necessary.
Obviously margins or such on the parent will be lost, but the children will not
wind up on the same line as anything they weren't already on the same line as.
E.g., if we split the parent of "bar" in foo<p>bar</p>, we get foo<br>bar, not
foobar. (This is amazingly complicated and error-prone.)
We don't preserve inline styles: callers that want to do that should call
record the values and restore the values themselves.
All this is useful in a lot of situations, like for outdenting. For inline formatting commands, we almost always rely on pushing down values instead, since that often leads to tidier markup.
- Let original parent be the parent of the first member of node list.
- If original parent is not editable or its parent is null, do nothing and abort these steps.
- If the first child of original parent is in node list, remove extraneous line breaks before original parent.
- If the first child of original parent is in node list, and original parent follows a line break, set follows line break to true. Otherwise, set follows line break to false.
- If the last child of original parent is in node list, and original parent precedes a line break, set precedes line break to true. Otherwise, set precedes line break to false.
-
If the first child of original parent is not in node list, but its last child is:
- For each node in node list, in reverse order, insert node into the parent of original parent immediately after original parent, preserving ranges.
- If precedes line break is true, and the last member of
node list does not precede a
line break, call
createElement("br")on the context object and insert the result immediately after the last member of node list. - Remove extraneous line breaks at the end of original parent.
- Abort these steps.
- If the first child of original parent is not in node
list:
- Let cloned parent be the result of calling
cloneNode(false)on original parent. - If original parent has an
idattribute, unset it. - Insert cloned parent into the parent of original parent immediately before original parent.
- While the
previousSiblingof the first member of node list is not null, append the first child of original parent as the last child of cloned parent, preserving ranges.
- Let cloned parent be the result of calling
-
For each node in node list, insert node into the parent of original parent immediately before original parent, preserving ranges.
- If follows line break is true, and the first member of
node list does not follow a
line break, call
createElement("br")on the context object and insert the result immediately before the first member of node list. - If the last member of node list is an inline node
other than a
br, and the first child of original parent is abr, and original parent is not an inline node, remove the first child of original parent from original parent. - If original parent has no children:
- Remove original parent from its parent.
- If precedes line break is true, and the last member of
node list does not precede a
line break, call
createElement("br")on the context object and insert the result immediately after the last member of node list.
- Otherwise, remove extraneous line breaks before original parent.
-
If node list's last member's
nextSiblingis null, but its parent is not null, remove extraneous line breaks at the end of node list's last member's parent.
To remove a node node while preserving its descendants, split the parent of node's children if it has any. If it has no children, instead remove it from its parent.
Canonical space sequences
Whitespace in HTML normally collapses. However, if the user hits the space bar twice in an HTML editor, they expect to see two spaces, not one. Even if they hit the space bar once at the beginning or end of a line, it would collapse without special handling. The only good solution here is for the author to set white-space: pre-wrap on the editable area, and on everywhere the content is reproduced. But if they don't, we have to painfully hack around the problem.
This is a basically intractable problem because of the unfortunate
confluence of three factors. One, our characters are Unicode, and Unicode
doesn't know about whitespace collapsing, so it provides no special characters
to control it. Two, HTML itself provides no features that control whitespace
collapsing without undesired side effects (like inhibiting line breaks or not
being allowed inside <p>). Three, we need to support
user agents that don't reliably support CSS, since that includes many popular
mail clients.
The upshot is we have no good way to control whitespace collapse, so we rely
on the least bad way available: . This doesn't
collapse with adjacent whitespace in browsers, which is good. But it also
doesn't allow a line break opportunity, which is bad. In any run of whitespace
that we don't want to collapse, any two regular spaces must be separated by an
so they don't collapse together, but we need to
carefully limit runs of consecutive s to minimize
the damage to line-breaking behavior.
The result is an elaborate and meticulously-crafted hodgepodge of bad compromises that frankly isn't worth the effort to explain here. The saving grace is that it all gets disabled if white-space is set to pre-wrap as it should be, so authors can opt out of the insanity. Interested readers will find detailed rationale for the exact sequences required in the comments.
The canonical space sequence of length n, with boolean flags non-breaking start and non-breaking end, is returned by the following algorithm:
- If n is zero, return the empty string.
- If n is one and both non-breaking start and non-breaking end are false, return a single space (U+0020).
- If n is one, return a single non-breaking space (U+00A0).
- Let buffer be the empty string.
- If non-breaking start is true, let repeated pair be U+00A0 U+0020. Otherwise, let it be U+0020 U+00A0.
- While n is greater than three, append repeated pair to buffer and subtract two from n.
- If n is three, append a three-code unit string to
buffer depending on non-breaking start and
non-breaking end:
- non-breaking start and non-breaking end false
- U+0020 U+00A0 U+0020
- non-breaking start true, non-breaking end false
- U+00A0 U+00A0 U+0020
- non-breaking start false, non-breaking end true
- U+0020 U+00A0 U+00A0
- non-breaking start and non-breaking end both true
- U+00A0 U+0020 U+00A0
- Otherwise, append a two-code unit string to buffer depending
on non-breaking start and non-breaking end:
- non-breaking start and non-breaking end false
- non-breaking start true, non-breaking end false
- U+00A0 U+0020
- non-breaking start false, non-breaking end true
- U+0020 U+00A0
- non-breaking start and non-breaking end both true
- U+00A0 U+00A0
- non-breaking start and non-breaking end false
- Return buffer.
To canonicalize whitespace at (node, offset), given an optional boolean argument fix collapsed space that defaults to true:
- If node is neither editable nor an editing host, abort these steps.
- Let start node equal node and let start offset equal offset.
-
Repeat the following steps:
- If start node has a child in the same editing host with index start offset minus one, set start node to that child, then set start offset to start node's length.
-
Otherwise, if start offset is zero and start node does not follow a line break and start node's parent is in the same editing host, set start offset to start node's index, then set start node to its parent.
- Otherwise, if start node is a
Textnode and its parent's resolved value for "white-space" is neither "pre" nor "pre-wrap" and start offset is not zero and the (start offset − 1)st code unit of start node'sdatais a space (0x0020) or non-breaking space (0x00A0), subtract one from start offset. - Otherwise, break from this loop.
-
Let end node equal start node and end offset equal start offset.
- Let length equal zero.
-
Let collapse spaces be true if start offset is zero and start node follows a line break, otherwise false.
- Repeat the following steps:
- If end node has a child in the same editing host with index end offset, set end node to that child, then set end offset to zero.
-
Otherwise, if end offset is end node's length and end node does not precede a line break and end node's parent is in the same editing host, set end offset to one plus end node's index, then set end node to its parent.
- Otherwise, if end node is a
Textnode and its parent's resolved value for "white-space" is neither "pre" nor "pre-wrap" and end offset is not end node's length and the end offsetth code unit of end node'sdatais a space (0x0020) or non-breaking space (0x00A0):- If fix collapsed space is true, and collapse
spaces is true, and the end offsetth code unit of
end node's
datais a space (0x0020): calldeleteData(end offset, 1)on end node, then continue this loop from the beginning. - Set collapse spaces to true if the end offsetth
code unit of end node's
datais a space (0x0020), false otherwise. - Add one to end offset.
- Add one to length.
- If fix collapsed space is true, and collapse
spaces is true, and the end offsetth code unit of
end node's
- Otherwise, break from this loop.
-
If fix collapsed space is true, then while (start node, start offset) is before (end node, end offset):
- If end node has a child in the same editing host with index end offset − 1, set end node to that child, then set end offset to end node's length.
- Otherwise, if end offset is zero and end node's parent is in the same editing host, set end offset to end node's index, then set end node to its parent.
- Otherwise, if end node is a
Textnode and its parent's resolved value for "white-space" is neither "pre" nor "pre-wrap" and end offset is end node's length and the last code unit of end node'sdatais a space (0x0020) and end node precedes a line break:- Subtract one from end offset.
- Subtract one from length.
- Call
deleteData(end offset, 1)on end node.
- Otherwise, break from this loop.
-
Let replacement whitespace be the canonical space sequence of length length. non-breaking start is true if start offset is zero and start node follows a line break, and false otherwise. non-breaking end is true if end offset is end node's
lengthand end node precedes a line break, and false otherwise. - While (start node, start offset) is before
(end node, end offset):
- If start node has a child with index start offset, set start node to that child, then set start offset to zero.
- Otherwise, if start node is not a
Textnode or if start offset is start node's length, set start offset to one plus start node's index, then set start node to its parent. - Otherwise:
- Remove the first code unit from replacement whitespace, and let element be that code unit.
- If element is not the same as the start
offsetth code unit of start node's
data:-
Call
insertData(start offset, element)on start node. - Call
deleteData(start offset + 1, 1)on start node.
-
- Add one to start offset.
Indenting and outdenting
There are two basically different types of indent/outdent: lists, and
everything else. For lists we'll wrap the item in a nested list to indent, and
split its parent to outdent. For
everything else we'll wrap in a <blockquote> to indent,
and try breaking it out of an ancestor indentation element to
outdent.
Indenting winds up being pretty simple: just add an appropriate wrapper.
There's not really anything to think about here except which wrapper we want
(<ol> or <ul> or <blockquote>), and establishing that is not rocket science.
Outdenting is considerably more complicated. The basic idea we follow is to first find the nearest editable ancestor that's a list or indentation element. If we succeed, and the node we're trying to outdent is the only descendant of the ancestor, of course we can just remove the ancestor and that's that. Otherwise, what we do is remove the ancestor and then indent all its other descendants, much like pushing down values.
But of course, there are complications. We don't always actually want to
remove the closest ancestor that's causing indentation. For one
thing, we prefer ancestors that we can remove completely, i.e., simple indentation elements. When
outdenting <blockquote><blockquote
id="abc">foo</blockquote></blockquote>, removing the inner tag
would result in <blockquote><div
id="abc">foo</div></blockquote>, since we don't want to lose the
id. Thus we prefer to remove the outer tag and wind up with <blockquote id="abc">foo</blockquote>.
Also, if the node we're outdenting is itself a list, we prefer to remove an ancestor indentation element rather than the list. Otherwise, if the user selected some text, indented it, then added a list, there would be no way to remove the indentation without removing the list first. This way, the user could remove the list with the appropriate list-toggling command or remove the indentation with the outdent command.
To indent a list node list of consecutive sibling nodes:
- If node list is empty, do nothing and abort these steps.
- Let first node be the first member of node list.
- If first node's parent is an
olorul:- Let tag be the local name of the parent of first node.
-
Wrap node list, with sibling criteria returning true for an HTML element with local name tag and false otherwise, and new parent instructions returning the result of calling
createElement(tag)on theownerDocumentof first node. - Abort these steps.
-
Wrap node list, with sibling criteria returning true for a simple indentation element and false otherwise, and new parent instructions returning the result of calling
createElement("blockquote")on theownerDocumentof first node. Let new parent be the result. - Fix disallowed ancestors of new parent.
To outdent a node node:
- If node is not editable, abort these steps.
-
If node is a simple indentation element, remove node, preserving its descendants. Then abort these steps.
-
If node is an indentation element:
- Unset the
dirattribute of node, if any. - Unset the margin, padding, and border CSS properties of node.
- Set the tag name of node to "div".
- Abort these steps.
- Unset the
-
Let current ancestor be node's parent.
- Let ancestor list be a list of nodes, initially empty.
- While current ancestor is an editable
Elementthat is neither a simple indentation element nor anolnor aul, append current ancestor to ancestor list and then set current ancestor to its parent. - If current ancestor is not an editable simple indentation element:
-
If node is an
oloruland current ancestor is not an editable indentation element:- Unset the
reversed,start, andtypeattributes of node, if any are set. - Let children be the children of node.
-
If node has attributes, and its parent is not an
olorul, set the tag name of node to "div". - Otherwise:
- Record the values of node's children, and let values be the result.
- Remove node, preserving its descendants.
- Restore the values from values.
- Fix disallowed ancestors of each member of children.
- Abort these steps.
- Unset the
- If current ancestor is not an editable indentation element, abort these steps.
-
Append current ancestor to ancestor list.
-
Let original ancestor be current ancestor.
- While ancestor list is not empty:
- Let current ancestor be the last member of ancestor list.
- Remove the last member from ancestor list.
- Let target be the child of current ancestor that is equal to either node or the last member of ancestor list.
- If target is an inline node that is not a
br, and itsnextSiblingis abr, remove target'snextSiblingfrom its parent. - Let preceding siblings be the precedings siblings of target, and let following siblings be the followings siblings of target.
- Indent preceding siblings.
- Indent following siblings.
- Outdent original ancestor.
Toggling lists
This is the action for the insertOrderedList
command and the insertUnorderedList
command, which behave identically except for which list type they
target. It does several things that vary contextually.
If everything in the selection is contained in the target list type already, this more or less just outdents everything one step. This is relatively simple.
Otherwise, it's slightly more complicated:
First, any lists of the opposite list type (other tag name) get converted to the target list type (tag name). They get merged into a sibling if appropriate, otherwise we set the tag name.
Then we go through all the affected nodes, handling each run of consecutive
siblings separately. Any line that's not already wrapped in an <li> gets wrapped. If the parent at this point isn't a list at
all, the run gets wrapped in a list. If it's the wrong type of list, we
split the parent and rewrap it in the right type of list. That's
basically it, except that we have to exercise the usual care to try merging
with siblings and so forth.
To toggle lists, given a string tag name (either "ol" or "ul"):
- Let mode be "disable" if the selection's list state is tag name, and "enable" otherwise.
- Let other tag name be "ol" if tag name is "ul", and "ul" if tag name is "ol".
- Let items be a list of all
lis that are inclusive ancestors of the active range's start and/or end node. -
For each item in items, normalize sublists of item.
- Block-extend the active range, and let new range be the result.
- If mode is "enable", then let lists to convert
consist of every editable HTML element with
local name other tag name that is contained in new
range, and for every list in lists to convert:
-
If list's
previousSiblingornextSiblingis an editable HTML element with local name tag name:- Let children be list's children.
- Record the values of children, and let values be the result.
- Split the parent of children.
- Wrap children, with sibling criteria returning true for an HTML element with local name tag name and false otherwise.
- Restore the values from values.
- Otherwise, set the tag name of list to tag name.
-
- Let node list be a list of nodes, initially empty.
-
For each node node contained in new range, if node is editable; the last member of node list (if any) is not an ancestor of node; node is not an indentation element; and either node is an
olorul, or its parent is anolorul, or it is an allowed child of "li"; then append node to node list. -
If mode is "enable", remove from node list any
olorulwhose parent is not also anolorul. - If mode is "disable", then while node list is not
empty:
- Let sublist be an empty list of nodes.
- Remove the first member from node list and append it to sublist.
- If the first member of sublist is an HTML element with local name tag name, outdent it and continue this loop from the beginning.
- While node list is not empty, and the first member of
node list is the
nextSiblingof the last member of sublist and is not an HTML element with local name tag name, remove the first member from node list and append it to sublist. - Record the values of sublist, and let values be the result.
- Split the parent of sublist.
- Fix disallowed ancestors of each member of sublist.
- Restore the values from values.
- Otherwise, while node list is not empty:
- Let sublist be an empty list of nodes.
-
While either sublist is empty, or node list is not empty and its first member is the
nextSiblingof sublist's last member:-
If node list's first member is a
pordiv, set the tag name of node list's first member to "li", and append the result to sublist. Remove the first member from node list. - Otherwise, if the first member of node list is an
liorolorul, remove it from node list and append it to sublist. - Otherwise:
- Let nodes to wrap be a list of nodes, initially empty.
- While nodes to wrap is empty, or node list is
not empty and its first member is the
nextSiblingof nodes to wrap's last member and the first member of node list is an inline node and the last member of nodes to wrap is an inline node other than abr, remove the first member from node list and append it to nodes to wrap. - Wrap nodes to wrap, with new parent
instructions returning the result of calling
createElement("li")on the context object. Append the result to sublist.
-
-
If sublist's first member's parent is an HTML element with local name tag name, or if every member of sublist is an
olorul, continue this loop from the beginning. - If sublist's first member's parent is an HTML
element with local name other tag name:
- Record the values of sublist, and let values be the result.
- Split the parent of sublist.
- Wrap sublist, with sibling
criteria returning true for an HTML element with
local name tag name and false otherwise, and new
parent instructions returning the result of calling
createElement(tag name)on the context object. - Restore the values from values.
- Continue this loop from the beginning.
- Wrap sublist, with sibling criteria
returning true for an HTML element with local name tag
name and false otherwise, and new parent instructions
being the following:
-
If sublist's first member's parent is not an editable simple indentation element, or sublist's first member's parent's
previousSiblingis not an editable HTML element with local name tag name, callcreateElement(tag name)on the context object and return the result. - Let list be sublist's first member's
parent's
previousSibling. - Normalize sublists of list's
lastChild. - If list's
lastChildis not an editable HTML element with local name tag name, callcreateElement(tag name)on the context object, and append the result as the last child of list. - Return the last child of list.
-
- Fix disallowed ancestors of the previous step's result.
Justifying the selection
This is the action for the four justify* commands. It's pretty straightforward, with no notable
gotchas or special cases. It works more or less like a stripped-down version
of set the selection's value, except it gets to be much simpler
because it's much less general. (It's not similar enough to just invoke that
algorithm: too many things differ between block and inline elements.)
To justify the selection to a string alignment (either "center", "justify", "left", or "right"):
- Block-extend the active range, and let new range be the result.
-
Let element list be a list of all editable
Elements contained in new range that either has an attribute in the HTML namespace whose local name is "align", or has astyleattribute that sets "text-align", or is acenter. - For each element in element list:
- If element has an attribute in the HTML namespace whose local name is "align", remove that attribute.
- Unset the CSS property "text-align" on element, if it's set
by a
styleattribute. - If element is a
divorspanorcenterwith no attributes, remove it, preserving its descendants. - If element is a
centerwith one or more attributes, set the tag name of element to "div".
-
Block-extend the active range, and let new range be the result.
- Let node list be a list of nodes, initially empty.
-
For each node node contained in new range, append node to node list if the last member of node list (if any) is not an ancestor of node; node is editable; node is an allowed child of "div"; and node's alignment value is not alignment.
- While node list is not empty:
- Let sublist be a list of nodes, initially empty.
- Remove the first member of node list and append it to sublist.
- While node list is not empty, and the first member of
node list is the
nextSiblingof the last member of sublist, remove the first member of node list and append it to sublist. Wrap sublist. Sibling criteria returns true for any
divthat has one or both of the following two attributes and no other attributes, and false otherwise:- An
alignattribute whose value is an ASCII case-insensitive match for alignment. - A
styleattribute which sets exactly one CSS property (including unrecognized or invalid attributes), which is "text-align", which is set to alignment.
New parent instructions are to call
createElement("div")on the context object, then set its CSS property "text-align" to alignment and return the result.- An
Automatic linking
When the user inserts whitespace immediately following something
that looks like a URL or e-mail address, we automatically run the createLink command on it.
An autolinkable URL is a string of the following form:
-
Either a string matching the scheme pattern from RFC 3986 section 3.1 followed by the literal string
://, or the literal stringmailto:; followed by -
Zero or more characters other than space characters; followed by
-
A character that is not one of the ASCII characters
!"'(),-.:;<>[]`{}.
To autolink (node, end offset):
- While (node, end offset)'s previous equivalent point is not null, set it to its previous equivalent point.
- If node is not a
Textnode, or has anaancestor, do nothing and abort these steps. - Let search be the largest substring of node's
datawhose end is end offset and that contains no space characters. - If some substring of search is an autolinkable
URL:
- While there is no substring of node's
dataending at end offset that is an autolinkable URL, decrement end offset. - Let start offset be the start index of the longest substring
of node's
datathat is an autolinkable URL ending at end offset. - Let href be the substring of node's
datastarting at start offset and ending at end offset.
- While there is no substring of node's
- Otherwise, if some substring of search is a valid e-mail address:
- While there is no substring of node's
dataending at end offset that is a valid e-mail address, decrement end offset. - Let start offset be the start index of the longest substring
of node's
datathat is a valid e-mail address ending at end offset. - Let href be "mailto:" concatenated with the substring of
node's
datastarting at start offset and ending at end offset.
- While there is no substring of node's
- Otherwise, do nothing and abort these steps.
- Let original range be the active range.
- Create a new range with start (node, start offset) and end (node, end offset), and set the context object's selection's range to it.
- Take the action for "createLink", with value equal to href.
- Set the context object's selection's range to original range.
The delete command
This is the same as hitting backspace (see Additional requirements). The easy part is if the selection isn't collapsed: just delete the selection. But it turns out rich-text editors have a lot of special behaviors for hitting backspace with a collapsed selection. Most obviously, if there's a text node right before the cursor (maybe wrapped in some inline elements), we delete its last character. But some of the special cases we run into are:
- Invisible nodes are removed before anything else happens.
- An
<a>gets removed if you backspace while the cursor is right after it, so the link disappears. - A
<br>or<hr>or<img>gets deleted. - Backspacing at the start of most blocks merges with the previous block. (Visually, this is a matter of deleting a line break.)
- Backspacing at the start of an indentation element, or an
<li>or<dt>or<dd>that's at the beginning of a list, outdents the current block (rather than merging with the previous block). - Backspacing at the start of a table cell does nothing.
- Backspacing immediately after a table selects the table, so a second backspace deletes it.
- Backspacing at the start of a list item that's not at the beginning of a list merges with the previous list item, but keeps the contents on a separate line, so you have to hit backspace a second time to get them on the same line.
- If the active range is not
collapsed, delete the selection and return true. -
Canonicalize whitespace at the active range's start.
- Let node and offset be the active range's start node and offset.
-
Repeat the following steps:
-
If offset is zero and node's
previousSiblingis an editable invisible node, remove node'spreviousSiblingfrom its parent. - Otherwise, if node has a child with index offset − 1 and that child is an editable invisible node, remove that child from node, then subtract one from offset.
- Otherwise, if offset is zero and node is an inline node, or if node is an invisible node, set offset to the index of node, then set node to its parent.
-
Otherwise, if node has a child with index offset − 1 and that child is an editable
a, remove that child from node, preserving its descendants. Then return true. - Otherwise, if node has a child with index
offset − 1 and that child is not a block
node or a
bror animg, set node to that child, then set offset to the length of node. - Otherwise, break from this loop.
-
-
If node is a
Textnode and offset is not zero, or if node is a block node that has a child with index offset − 1 and that child is abrorhrorimg:- Call
collapse(node, offset)on the context object's selection. - Call
extend(node, offset − 1)on the context object's selection. - Delete the selection.
- Return true.
- Call
-
If node is an inline node, return true.
-
If node is an
liordtorddand is the first child of its parent, and offset is zero:- Let items be a list of all
lis that are ancestors of node. - Normalize sublists of each item in items.
- Record the values of the one-node list consisting of node, and let values be the result.
- Split the parent of the one-node list consisting of node.
- Restore the values from values.
-
If node is a
ddordt, and it is not an allowed child of any of its ancestors in the same editing host, set the tag name of node to the default single-line container name and let node be the result. - Fix disallowed ancestors of node.
- Return true.
- Let items be a list of all
-
Let start node equal node and let start offset equal offset.
- Repeat the following steps:
-
If offset is zero, and node has an editable inclusive ancestor in the same editing host that's an indentation element:
- Block-extend the range whose start and end are both (node, 0), and let new range be the result.
- Let node list be a list of nodes, initially empty.
- For each node current node contained in new range, append current node to node list if the last member of node list (if any) is not an ancestor of current node, and current node is editable but has no editable descendants.
- Outdent each node in node list.
- Return true.
-
If the child of start node with index start offset is a
table, return true. -
If start node has a child with index start offset − 1, and that child is a
table:- Call
collapse(start node, start offset − 1)on the context object's selection. - Call
extend(start node, start offset)on the context object's selection. - Return true.
- Call
-
If offset is zero; and either the child of start node with index start offset minus one is an
hr, or the child is abrwhosepreviousSiblingis either abror not an inline node:- Call
collapse(start node, start offset − 1)on the context object's selection. - Call
extend(start node, start offset)on the context object's selection. - Delete the selection.
- Call
collapse(node, offset)on the selection. - Return true.
- Call
-
If the child of start node with index start offset is an
liordtordd, and that child'sfirstChildis an inline node, and start offset is not zero:- Let previous item be the child of start node with index start offset minus one.
-
If previous item's
lastChildis an inline node other than abr, callcreateElement("br")on the context object and append the result as the last child of previous item. - If previous item's
lastChildis an inline node, callcreateElement("br")on the context object and append the result as the last child of previous item.
-
If start node's child with index start offset is an
liordtordd, and that child'spreviousSiblingis also anliordtordd:- Call
cloneRange()on the active range, and let original range be the result. - Set start node to its child with index start offset − 1.
- Set start offset to start node's length.
- Set node to start node's
nextSibling. - Call
collapse(start node, start offset)on the context object's selection. - Call
extend(node, 0)on the context object's selection. - Delete the selection.
- Call
removeAllRanges()on the context object's selection. - Call
addRange(original range)on the context object's selection. - Return true.
- Call
-
While start node has a child with index start offset minus one:
- Call
collapse(start node, start offset)on the context object's selection. - Call
extend(node, offset)on the context object's selection. - Delete the selection, with direction "backward".
- Return true.
The formatBlock command
This command lets you change what block element particular lines are wrapped in. It will convert an existing wrapper if one exists, and otherwise will create a new one.
A formattable block name is "address", "dd", "div", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "p", or "pre".
-
If value begins with a "<" character and ends with a ">" character, remove the first and last characters from it.
- Let value be converted to ASCII lowercase.
-
If value is not a formattable block name, return false.
- Block-extend the active range, and let new range be the result.
- Let node list be an empty list of nodes.
- For each node node contained in new range,
append node to node list if it is
editable, the last member of original node list (if
any) is not an ancestor of node, node is either a
non-list single-line container or an allowed child
of "p" or a
ddordt, and node is not the ancestor of a prohibited paragraph child. - Record the values of node list, and let values be the result.
-
For each node in node list, while node is the descendant of an editable HTML element in the same editing host, whose local name is a formattable block name, and which is not the ancestor of a prohibited paragraph child, split the parent of the one-node list consisting of node.
- Restore the values from values.
-
While node list is not empty:
- If the first member of node list is a single-line
container:
-
Let sublist be the children of the first member of node list.
- Record the values of sublist, and let values be the result.
- Remove the first member of node list from its parent, preserving its descendants.
- Restore the values from values.
- Remove the first member from node list.
-
- Otherwise:
- Let sublist be an empty list of nodes.
- Remove the first member of node list and append it to sublist.
- While node list is not empty, and the first member of
node list is the
nextSiblingof the last member of sublist, and the first member of node list is not a single-line container, and the last member of sublist is not abr, remove the first member of node list and append it to sublist.
- Wrap sublist. If value is "div" or
"p", sibling criteria returns false; otherwise it returns true
for an HTML element with local name value and no
attributes, and false otherwise. New parent instructions
return the result of running
createElement(value)on the context object. Then fix disallowed ancestors of the result.
- If the first member of node list is a single-line
container:
- Return true.
- If the active range is null, return the empty string.
- Block-extend the active range, and let new range be the result.
- Let node list be all visible editable nodes that are contained in new range and have no children.
- If node list is empty, return false.
- Let type be null.
- For each node in node list:
- While node's parent is editable and in the same editing host as node, and node is not an HTML element whose local name is a formattable block name, set node to its parent.
- Let current type be the empty string.
- If node is an editable HTML element whose local name is a formattable block name, and node is not the ancestor of a prohibited paragraph child, set current type to node's local name.
- If type is null, set type to current type.
- Otherwise, if type does not equal current type, return true.
- Return false.
- If the active range is null, return the empty string.
- Block-extend the active range, and let new range be the result.
- Let node be the first visible editable node that is contained in new range and has no children. If there is no such node, return the empty string.
-
While node's parent is editable and in the same editing host as node, and node is not an HTML element whose local name is a formattable block name, set node to its parent.
-
If node is an editable HTML element whose local name is a formattable block name, and node is not the ancestor of a prohibited paragraph child, return node's local name, converted to ASCII lowercase.
- Return the empty string.
The forwardDelete command
This is the same as hitting the delete key (see Additional requirements). It behaves much
the same as the delete command, except of
course backwards. Also, some of the special cases for backspacing don't apply,
as noted in the comments. The one special case you get when deleting forward
but not backward is that if the cursor is before a grapheme cluster that
consists of multiple characters, like a base character with combining
diacritics, we delete the diacritics too. (Backspacing just deletes the last
diacritic, so you have to backspace several times to remove the whole cluster.)
- If the active range is not
collapsed, delete the selection and return true. - Canonicalize whitespace at the active range's start.
- Let node and offset be the active range's start node and offset.
- Repeat the following steps:
- If offset is the length of node and
node's
nextSiblingis an editable invisible node, remove node'snextSiblingfrom its parent. - Otherwise, if node has a child with index offset and that child is an editable invisible node, remove that child from node.
- Otherwise, if offset is the length of node and node is an inline node, or if node is invisible, set offset to one plus the index of node, then set node to its parent.
-
Otherwise, if node has a child with index offset and that child is neither a block node nor a
brnor animgnor a collapsed block prop, set node to that child, then set offset to zero. - Otherwise, break from this loop.
- If offset is the length of node and
node's
- If node is a
Textnode and offset is not node's length:- Let end offset be offset plus one.
-
While end offset is not node's length and the end offsetth code unit of node's
datahas general category M when interpreted as a Unicode code point, add one to end offset. - Call
collapse(node, offset)on the context object's selection. - Call
extend(node, end offset)on the context object's selection. - Delete the selection.
- Return true.
- If node is an inline node, return true.
- If node has a child with index offset and
that child is a
brorhrorimg, but is not a collapsed block prop:- Call
collapse(node, offset)on the context object's selection. - Call
extend(node, offset + 1)on the context object's selection. - Delete the selection.
- Return true.
- Call
-
Let end node equal node and let end offset equal offset.
- If end node has a child with index end offset, and that child is a collapsed block prop, add one to end offset.
- Repeat the following steps:
-
If the child of end node with index end offset minus one is a
table, return true. - If the child of end node with index end
offset is a
table:- Call
collapse(end node, end offset)on the context object's selection. - Call
extend(end node, end offset + 1)on the context object's selection. - Return true.
- Call
-
If offset is the length of node, and the child of end node with index end offset is an
hrorbr:- Call
collapse(end node, end offset)on the context object's selection. - Call
extend(end node, end offset + 1)on the context object's selection. - Delete the selection.
- Call
collapse(node, offset)on the selection. - Return true.
- Call
- Call
collapse(node, offset)on the context object's selection. - Call
extend(end node, end offset)on the context object's selection. - Delete the selection.
The indent command
- Let items be a list of all
lis that are inclusive ancestors of the active range's start and/or end node. -
For each item in items, normalize sublists of item.
- Block-extend the active range, and let new range be the result.
- Let node list be a list of nodes, initially empty.
- For each node node contained in new range, if node is editable and is an allowed child of "div" or "ol" and if the last member of node list (if any) is not an ancestor of node, append node to node list.
-
If the first visible member of node list is an
liwhose parent is anolorul:- Let sibling be node list's first
visible member's
previousSibling. - While sibling is invisible, set
sibling to its
previousSibling. - If sibling is an
li, normalize sublists of sibling.
- Let sibling be node list's first
visible member's
- While node list is not empty:
- Let sublist be a list of nodes, initially empty.
- Remove the first member of node list and append it to sublist.
- While the first member of node list is the
nextSiblingof the last member of sublist, remove the first member of node list and append it to sublist. - Indent sublist.
The insertHorizontalRule command
- Let start node, start offset, end node, and end offset be the active range's start and end nodes and offsets.
- While start offset is 0 and start node's parent is not null, set start offset to start node's index, then set start node to its parent.
- While end offset is end node's length, and end node's parent is not null, set end offset to one plus end node's index, then set end node to its parent.
- Call
collapse(start node, start offset)on the context object's selection. - Call
extend(end node, end offset)on the context object's selection. - Delete the selection, with block merging false.
- If the active range's start node is neither editable nor an editing host, return true.
-
If the active range's start node is a
Textnode and its start offset is zero, callcollapse()on the context object's selection, with first argument the active range's start node's parent and second argument the active range's start node's index. - If the active range's start node is a
Textnode and its start offset is the length of its start node, callcollapse()on the context object's selection, with first argument the active range's start node's parent, and the second argument one plus the active range's start node's index. - Let hr be the result of calling
createElement("hr")on the context object. - Run
insertNode(hr)on the active range. -
Fix disallowed ancestors of hr.
- Run
collapse()on the context object's selection, with first argument hr's parent and the second argument equal to one plus hr's index. - Return true.
The insertHTML command
- If the active range's start node is neither editable nor an editing host, return true.
-
Let frag be the result of calling
createContextualFragment(value)on the active range. - Let last child be the
lastChildof frag. -
If last child is null, return true.
- Let descendants be all descendants of frag.
-
If the active range's start node is a block node:
- Let collapsed block props be all editable collapsed block prop children of the active range's start node that have index greater than or equal to the active range's start offset.
- For each node in collapsed block props, remove node from its parent.
-
Call
insertNode(frag)on the active range. -
If the active range's start node is a block node with no visible children, call
createElement("br")on the context object and append the result as the last child of the active range's start node. -
Call
collapse()on the context object's selection, with last child's parent as the first argument and one plus its index as the second. -
Fix disallowed ancestors of each member of descendants.
- Return true.
The insertImage command
-
If value is the empty string, return false.
-
Delete the selection, with strip wrappers false.
- Let range be the active range.
- If the active range's start node is neither editable nor an editing host, return true.
-
If range's start node is a block node whose sole child is a
br, and its start offset is 0, remove its start node's child from it. - Let img be the result of calling
createElement("img")on the context object. -
Run
setAttribute("src", value)on img. -
Run
insertNode(img)on range. - Let selection be the result of calling
getSelection()on the context object. - Run
collapse()on selection, with first argument equal to the parent of img and the second argument equal to one plus the index of img. - Return true.
The insertLineBreak command
This is the same as hitting Shift-Enter or such (see Additional requirements). It deletes the
selection, and replaces it with a <br>. No real
complications.
-
Delete the selection, with strip wrappers false.
- If the active range's start node is neither editable nor an editing host, return true.
-
If the active range's start node is an
Element, and "br" is not an allowed child of it, return true. - If the active range's start node is not an
Element, and "br" is not an allowed child of the active range's start node's parent, return true. -
If the active range's start node is a
Textnode and its start offset is zero, callcollapse()on the context object's selection, with first argument equal to the active range's start node's parent and second argument equal to the active range's start node's index. - If the active range's start node is a
Textnode and its start offset is the length of its start node, callcollapse()on the context object's selection, with first argument equal to the active range's start node's parent and second argument equal to one plus the active range's start node's index. - Let br be the result of calling
createElement("br")on the context object. - Call
insertNode(br)on the active range. - Call
collapse()on the context object's selection, with br's parent as the first argument and one plus br's index as the second argument. - If br is a collapsed line break, call
createElement("br")on the context object and let extra br be the result, then callinsertNode(extra br)on the active range. - Return true.
The insertOrderedList command
Action: Toggle lists with tag name "ol", then return true.
Indeterminate: True if the selection's list state is "mixed" or "mixed ol", false otherwise.
State: True if the selection's list state is "ol", false otherwise.
The insertParagraph command
This is the same as hitting enter (see Additional requirements). The general rule is that we find the nearest single-line container ancestor, clone it and insert the clone after it, and then move all the contents after the cursor (along with the cursor itself) to the clone. But there are a few special cases:
- If we can't find a single-line container to use, first we wrap the current line in a new container with the default single-line container name.
- For
<address>,<listing>, and<pre>, we add a<br>instead of cloning it. These are all elements that are meant to contain multiple lines, not have one line per element. - If the cursor is in a list item with no contents, hitting enter breaks out of the list entirely, outdenting the current item. This means that if you're in a list, you can hit enter twice to break out.
- If the cursor is at the end of a heading, hitting enter doesn't make a new heading, it switches to the default single-line container name.
- If the cursor is at the end of a
<dt>or<dd>, the new element is the opposite type, so you naturally switch between entering terms and definitions.
- Delete the selection.
- If the active range's start node is neither editable nor an editing host, return true.
- Let node and offset be the active range's start node and offset.
- If node is a
Textnode, and offset is neither 0 nor the length of node, callsplitText(offset)on node. - If node is a
Textnode and offset is its length, set offset to one plus the index of node, then set node to its parent. - If node is a
TextorCommentnode, set offset to the index of node, then set node to its parent. - Call
collapse(node, offset)on the context object's selection. - Let container equal node.
- While container is not a single-line container, and container's parent is editable and in the same editing host as node, set container to its parent.
-
If container is an editable single-line container in the same editing host as node, and its local name is "p" or "div":
-
If container is not editable or not in the same editing host as node or is not a single-line container:
- Let tag be the default single-line container name.
- Block-extend the active range, and let new range be the result.
- Let node list be a list of nodes, initially empty.
- Append to node list the first node in tree order that is contained in new range and is an allowed child of "p", if any.
- If node list is empty:
-
If tag is not an allowed child of the active range's start node, return true.
- Set container to the result of calling
createElement(tag)on the context object. - Call
insertNode(container)on the active range. - Call
createElement("br")on the context object, and append the result as the last child of container. - Call
collapse(container, 0)on the context object's selection. - Return true.
-
-
While the
nextSiblingof the last member of node list is not null and is an allowed child of "p", append it to node list. - Wrap node list, with sibling
criteria returning false and new parent instructions
returning the result of calling
createElement(tag)on the context object. Set container to the result.
-
If container's local name is "address", "listing", or "pre":
- Let br be the result of calling
createElement("br")on the context object. - Call
insertNode(br)on the active range. - Call
collapse(node, offset + 1)on the context object's selection. -
If br is the last descendant of container, let br be the result of calling
createElement("br")on the context object, then callinsertNode(br)on the active range. - Return true.
- Let br be the result of calling
-
If container's local name is "li", "dt", or "dd"; and either it has no children or it has a single child and that child is a
br:- Split the parent of the one-node list consisting of container.
- If container has no children, call
createElement("br")on the context object and append the result as the last child of container. -
If container is a
ddordt, and it is not an allowed child of any of its ancestors in the same editing host, set the tag name of container to the default single-line container name and let container be the result. - Fix disallowed ancestors of container.
- Return true.
- Let new line range be a new range whose start is the same as the active range's, and whose end is (container, length of container).
-
While new line range's start offset is zero and its start node is not a prohibited paragraph child, set its start to (parent of start node, index of start node).
- While new line range's start offset is the length of its start node and its start node is not a prohibited paragraph child, set its start to (parent of start node, 1 + index of start node).
- Let end of line be true if new line range
contains either nothing or a single
br, and false otherwise. -
If the local name of container is "h1", "h2", "h3", "h4", "h5", or "h6", and end of line is true, let new container name be the default single-line container name.
-
Otherwise, if the local name of container is "dt" and end of line is true, let new container name be "dd".
- Otherwise, if the local name of container is "dd" and end of line is true, let new container name be "dt".
- Otherwise, let new container name be the local name of container.
- Let new container be the result of calling
createElement(new container name)on the context object. - Copy all attributes of container to new container.
- If new container has an
idattribute, unset it. - Insert new container into the parent of container immediately after container.
- Let contained nodes be all nodes contained in new line range.
-
Let frag be the result of calling
extractContents()on new line range. - Unset the
idattribute (if any) of eachElementdescendant of frag that is not in contained nodes. - Call
appendChild(frag)on new container. -
While container's
lastChildis a prohibited paragraph child, set container to itslastChild. - While new container's
lastChildis a prohibited paragraph child, set new container to itslastChild. - If container has no visible children, call
createElement("br")on the context object, and append the result as the last child of container. -
If new container has no visible children, call
createElement("br")on the context object, and append the result as the last child of new container. - Call
collapse(new container, 0)on the context object's selection. - Return true.
The insertText command
This is the same as typing text (see Additional requirements). If the input string is more than one character, first we split it up into one execution per character, for simplicity. The general rule is then that we record each command's state override or value override, insert the new character and select it, restore any overrides that we saved, and collapse the selection to its end.
The idea of the override business is that the user might run a command like bold when the selection is collapsed. There's nothing to bold in that case, but if the user runs bold and then types a character, they expect it to be bold. Thus we save the requested state in an override and restore it when the user types. Deleting things can also set overrides, if the deleted text was styled.
Whitespace is a special case. The note for canonical space sequences gives some of the background. If the user tries typing a space, we make it non-breaking so it doesn't collapse with anything, then canonicalize whitespace around the insertion point so line breaking isn't adversely affected.
One last special case is a newline. For that we just pass off to the
insertParagraph command.
-
Delete the selection, with strip wrappers false.
- If the active range's start node is neither editable nor an editing host, return true.
- If value's length is greater than one:
- For each code unit el in value, take the
action for the
insertTextcommand, with value equal to el. - Return true.
- For each code unit el in value, take the
action for the
- If value is the empty string, return true.
-
If value is a newline (U+00A0), take the action for the
insertParagraphcommand and return true. - Let node and offset be the active range's start node and offset.
-
If node has a child whose index is offset − 1, and that child is a
Textnode, set node to that child, then set offset to node's length. - If node has a child whose index is offset,
and that child is a
Textnode, set node to that child, then set offset to zero. - Record current overrides, and let overrides be the result.
- Call
collapse(node, offset)on the context object's selection. - Canonicalize whitespace at (node, offset).
- Let (node, offset) be the active range's start.
- If node is a
Textnode:- Call
insertData(offset, value)on node. - Call
collapse(node, offset)on the context object's selection. - Call
extend(node, offset + 1)on the context object's selection.
- Call
- Otherwise:
-
If node has only one child, which is a collapsed line break, remove its child from it.
- Let text be the result of calling
createTextNode(value)on the context object. - Call
insertNode(text)on the active range. - Call
collapse(text, 0)on the context object's selection. - Call
extend(text, 1)on the context object's selection.
-
- Restore states and values from overrides.
- Canonicalize whitespace at the active range's start, with fix collapsed space false.
- Canonicalize whitespace at the active range's end, with fix collapsed space false.
- If value is a space character, autolink the active range's start.
- Call
collapseToEnd()on the context object's selection. - Return true.
The insertUnorderedList command
Action: Toggle lists with tag name "ul", then return true.
Indeterminate: True if the selection's list state is "mixed" or "mixed ul", false otherwise.
State: True if the selection's list state is "ul", false otherwise.
The justifyCenter command
Action: Justify the selection with alignment "center", then return true.
Indeterminate: Return false if the active range is null. Otherwise, block-extend the active range. Return true if among visible editable nodes that are contained in the result and have no children, at least one has alignment value "center" and at least one does not. Otherwise return false.
State: Return false if the active range is null. Otherwise, block-extend the active range. Return true if there is at least one visible editable node that is contained in the result and has no children, and all such nodes have alignment value "center". Otherwise return false.
Value: Return the empty string if the active range is null. Otherwise, block-extend the active range, and return the alignment value of the first visible editable node that is contained in the result and has no children. If there is no such node, return "left".
The justifyFull command
Action: Justify the selection with alignment "justify", then return true.
Indeterminate: Return false if the active range is null. Otherwise, block-extend the active range. Return true if among visible editable nodes that are contained in the result and have no children, at least one has alignment value "justify" and at least one does not. Otherwise return false.
State: Return false if the active range is null. Otherwise, block-extend the active range. Return true if there is at least one visible editable node that is contained in the result and has no children, and all such nodes have alignment value "justify". Otherwise return false.
Value: Return the empty string if the active range is null. Otherwise, block-extend the active range, and return the alignment value of the first visible editable node that is contained in the result and has no children. If there is no such node, return "left".
The justifyLeft command
Action: Justify the selection with alignment "left", then return true.
Indeterminate: Return false if the active range is null. Otherwise, block-extend the active range. Return true if among visible editable nodes that are contained in the result and have no children, at least one has alignment value "left" and at least one does not. Otherwise return false.
State: Return false if the active range is null. Otherwise, block-extend the active range. Return true if there is at least one visible editable node that is contained in the result and has no children, and all such nodes have alignment value "left". Otherwise return false.
Value: Return the empty string if the active range is null. Otherwise, block-extend the active range, and return the alignment value of the first visible editable node that is contained in the result and has no children. If there is no such node, return "left".
The justifyRight command
Action: Justify the selection with alignment "right", then return true.
Indeterminate: Return false if the active range is null. Otherwise, block-extend the active range. Return true if among visible editable nodes that are contained in the result and have no children, at least one has alignment value "right" and at least one does not. Otherwise return false.
State: Return false if the active range is null. Otherwise, block-extend the active range. Return true if there is at least one visible editable node that is contained in the result and has no children, and all such nodes have alignment value "right". Otherwise return false.
Value: Return the empty string if the active range is null. Otherwise, block-extend the active range, and return the alignment value of the first visible editable node that is contained in the result and has no children. If there is no such node, return "left".
The outdent command
- Let items be a list of all
lis that are inclusive ancestors of the active range's start and/or end node. -
For each item in items, normalize sublists of item.
- Block-extend the active range, and let new range be the result.
- Let node list be a list of nodes, initially empty.
-
For each node node contained in new range, append node to node list if the last member of node list (if any) is not an ancestor of node; node is editable; and either node has no editable descendants, or is an
olorul, or is anliwhose parent is anolorul. - While node list is not empty:
- While the first member of node list is an
olorulor is not the child of anolorul, outdent it and remove it from node list. - If node list is empty, break from these substeps.
- Let sublist be a list of nodes, initially empty.
- Remove the first member of node list and append it to sublist.
- While the first member of node list is the
nextSiblingof the last member of sublist, and the first member of node list is not anolorul, remove the first member of node list and append it to sublist. - Record the values of sublist, and let values be the result.
- Split the parent of sublist.
- Fix disallowed ancestors of each member of sublist.
- Restore the values from values.
- While the first member of node list is an
- Return true.
Miscellaneous commands
The copy command
Action: The user agent must either copy the current selection
to the clipboard as though the user had requested it, or throw a
SecurityError exception. This specification does not define exactly how the
selection is to be copied to the clipboard, but the Clipboard API and
events specification might be useful.
User agents should exercise caution in respecting this command, because sites could abuse it to confuse and annoy the user by overwriting the clipboard with extremely long, obscene, or otherwise objectionable content.
User agents may choose not to support this
command at all. If a user agent will only honor the
command for some whitelisted sites depending on configuration, it
may either throw a SecurityError exception for non-whitelisted sites,
or it may act as though the command is unsupported on those sites.
The cut command
Action: The user agent must either copy the current selection
to the clipboard and then delete it, as though the user had requested it, or
throw a SecurityError exception. This specification does not define
exactly how the selection is to be deleted or copied to the clipboard, but the
Clipboard API and
events specification might be useful.
User agents should exercise caution in respecting this command, because sites could abuse it to confuse and annoy the user by overwriting the clipboard with extremely long, obscene, or otherwise objectionable content.
User agents may choose not to support this
command at all. If a user agent will only honor the
command for some whitelisted sites depending on configuration, it
may either throw a SecurityError exception for non-whitelisted sites,
or it may act as though the command is unsupported on those sites.
The defaultParagraphSeparator command
This is a new feature, added by request in bug 15527. (Opera already had an o-defaultblock command that worked similarly.) If you are implementing this, please make sure to file any feedback as bugs. The spec is not finalized yet and can still be easily changed.
Action: Let value be converted to ASCII lowercase. If value is then equal to "p" or "div", set the context object's default single-line container name to value, then return true. Otherwise, return false.
Value: Return the context object's default single-line container name.
The paste command
Action: The user agent must either delete the
selection and then paste the clipboard's contents to the current cursor
position, as though the user had requested it, or throw a SecurityError
exception. This specification does not define exactly how the clipboard is to
be converted to HTML for pasting, but the Clipboard API and
events specification might be useful.
User agents should exercise caution in respecting this command, because sites could abuse it to read private information from the clipboard.
User agents may choose not to support this
command at all. If a user agent will only honor the
command for some whitelisted sites depending on configuration, it
may either throw a SecurityError exception for non-whitelisted sites,
or it may act as though the command is unsupported on those sites.
The redo command
Action: As defined by the UndoManager specification.
The selectAll command
This is totally broken: if executed inside an editing host, it has to select the editing host contents, not the whole document. See bug.
-
Let target be the body element of the context object.
If target is null, let target be the context object's
documentElement. - If target is null, call
getSelection()on the context object, and callremoveAllRanges()on the result. - Otherwise, call
getSelection()on the context object, and callselectAllChildren(target)on the result. - Return true.
The styleWithCSS command
Action: If value is an ASCII case-insensitive match for the string "false", set the CSS styling flag to false. Otherwise, set the CSS styling flag to true. Either way, return true.
State: True if the CSS styling flag is true, otherwise false.
The undo command
Action: As defined by the UndoManager specification.
The useCSS command
Action: If value is an ASCII case-insensitive match for the string "false", set the CSS styling flag to true. Otherwise, set the CSS styling flag to false. Either way, return true.
Since the effect of this command is the opposite of what one would expect,
user agents are encouraged to point authors to styleWithCSS when useCSS is used, such as by logging a warning to an error
console.
No state is defined for this command, so queryCommandState("useCSS") must always return
false. To query the CSS styling flag's current value, authors
have to use the styleWithCSS command.
Additional requirements
It has been suggested that some things here need to be platform-dependent, not fully standardized. For now I'm standardizing them anyway, because the large majority of behavior should be platform-agnostic. If anyone has suggestions as to particular things that should be left up to platform behavior, please say so.
When the user instructs the user agent to insert a line break inside an
editing host, such as by pressing the Enter key while the cursor
is in an editable node, the user agent must call
execCommand("insertparagraph") on the relevant
document.
When the user instructs the user agent to insert a line break inside an
editing host without breaking out of the current block, such as by
pressing Shift-Enter or Option-Enter while the cursor is in an
editable node, the user agent must call
execCommand("insertlinebreak") on the relevant
document.
When the user instructs the user agent to delete the previous character
inside an editing host, such as by pressing the Backspace key
while the cursor is in an editable node, the user agent must
call execCommand("delete") on the relevant
document.
When the user instructs the user agent to delete the next character inside
an editing host, such as by pressing the Delete key while the
cursor is in an editable node, the user agent must call
execCommand("forwarddelete") on the relevant
document.
When the user instructs the user agent to insert text inside an
editing host, such as by typing on the keyboard while the cursor
is in an editable node, the user agent must call
execCommand("inserttext", false, value)
on the relevant document, with value equal to the text the user
provided. If the user inserts multiple characters at once or in quick
succession, this specification does not define whether it is treated as one
insertion or several consecutive insertions.
The user agent may allow the user to make other changes to editable content,
such as causing Ctrl-B to call
execCommand("bold"). Any such change must
be accomplished by calling execCommand(), so that in particular,
"beforeinput" and "input" events fire as appropriate. The command
invoked should be one of the standard commands
defined in this specification if possible, and otherwise must be a
vendor-specific command.
Acknowledgements
This section is not normative.
Thanks to:
- Google and Mozilla, for funding this work
- Ian Hickson, for overseeing it initially
- Ian Hickson and Ms2ger, for starting the selection work
- Julie Parent, Ojan Vafai, Alex Russel, and Eric Seidel for their research on how browsers and other rich text editors behave in many common scenarios
- Ehsan Akhgari, Tab Atkins, Mathias Bynens, Tim Down, Markus Ernst, Daniel Glazman, Tali Gregor (née Fuss), Stig Halvorsen, Jeff Harris, Ian Hickson, Cameron Heavon-Jones, Anne van Kesteren, Alfonso Martínez de Lizarrondo, Glenn Maynard, Ms2ger, Ryosuke Niwa, Robert O'Callahan, Julie Parent, Simon Pieters, Michael A. Puls II, Rich Schwerdtfeger, Jonas Sicking, Henri Sivonen, Smylers, Hallvord R. M. Steen, Roland Steiner, Annie Sullivan, timeless, Ojan Vafai, Brett Zamir, and Boris Zbarsky for their feedback, participation, or other helpful contributions