Selection.setAnchor

These functions set the actual selection from the current internal position.

A selection has two major pieces, the anchor and the focus, and a third bookkeeping coordinate, called the user coordinate.

It is best to think about these by thinking about the user interface. When you click and drag in a text document, the point where you clicked is the anchor position. As you drag, it moves the focus position. The selection is all the text between the anchor and focus. The cursor (also known as the caret) is drawn at the focus point.

Meanwhile, the user coordinate is the point where the user last explicitly moved the focus. Try clicking near the end of a long line, then moving up past a short line, to another long line. Your cursor should remain near the column of the original click, even though the focus moved left while passing through the short line. The user coordinate is how this is achieved - explicit user action on the horizontal axis (like pressing the left or right arrows) sets the X coordinate with setUserXCoordinate, and explicit user action on the vertical axis sets the Y coordinate (like the up or down arrows) with setUserYCoordinate, leaving X alone even if the focus moved horizontally due to a shorter or longer line. They're only moved together if the user action worked on both axes together (like a mouse click) with the setUserCoordinate function. Note that setUserCoordinate remembers the column even if there is no glyph there, making it ideal for mouse interaction, whereas the setUserXCoordinate and setUserYCoordinate set it to the position of the glyph on the focus, making them more suitable for keyboard interaction.

Before you set one of these values, you move the internal position with the move family of functions (moveTo, moveLeft, etc.).

Setting the anchor also always sets the focus.

For example, to select the whole document:

with(selection) {
	moveToStartOfDocument(); // changes internal position without affecting the actual selection
	setAnchor(); // set the anchor, actually changing the selection.
	// Note that setting the anchor also always sets the focus, so the selection is empty at this time.
	moveToEndOfDocument(); // move the internal position to the end
	setFocus(); // and now set the focus, which extends the selection from the anchor, meaning the whole document is selected now
}

I didn't set the user coordinate there since the user's action didn't specify a row or column.

struct Selection
setAnchor
()

Meta