2005-04-18

Editors don't need a getCaretPosition method

There are lots of well known convenient simplifications/generalizations when writing text editors.

For example: the selection is just a special case of a range highlighter, which is a concept useful for displaying find matches or misspellings and so on.

Or: there's no need to keep track of an insertion point and a selected range; the former is the special case of the empty selection. (Though as far as I know, if you want traditional keyboard selection, you will have to keep track of which end is the anchor.)

And: the one true primitive is replaceRange; a removal is a replaceRange with an empty replacement, an insertion is a replaceRange with an empty range.

They're all pretty traditional, but there's one I hadn't come across until our latest editor-writing adventure: not only don't you need getCaretPosition, you're better off without it. If you can't ask where the caret is, you're forced to think about the selection. What does the operation I'm writing mean if there's a non-empty selection? Do I want the selection start, the selection end, or do I want to behave differently depending on whether the selection's empty or non-empty?

Maybe others have more natural discipline than I do, but I've found not having getCaretPosition a really useful way to force me to think about both cases, where I wouldn't have done previously.