I don't understand onDidRemoveSelection


I think I have a general misunderstanding of ranges from selection and often end up confusing the two. That said, here’s my problem: I want to detect once a selected text in an editor pane has been deselected.

# pre-requisites
editor = atom.workspace.getActiveTextEditor();
selection = editor.getLastSelection()
console.log selection.getText()

All of the above works fine, it logs the text of the selection to the console. So, let’s go ahead.

Using editor.onDidChangeSelectionRange detects whenever I’m changing the selection (as the name suggests), but it always seems to be a step behind. Judging by its name, I should be using onDidRemoveSelection in the first place. The problem is, that the following never logs anything.

editor.onDidRemoveSelection () ->
  console.log "Cuckoo!"

What am I doing wrong?


onDidRemoveSelection only gets called when a selection from the list of selections an editor maintains is removed from that list and destroyed. So, if you select something and then select something else, no selections are removed and the handler isn’t called. It also helps to know that cursors are zero-length selections in the eyes of the editor. So if you select a single range and then click someplace to dismiss the selection, you haven’t removed a selection because there is always a minimum of one selection, your cursor.

But if you select all the instances of “Atom” in the README.md of the atom/atom repository using Cmd+D and then click someplace, you’ll trigger the onDidRemoveSelection event once for every selection that you had greater than one.