Some scripting questions about retrieving characters related to cursor or selection


How do I:

  1. Get the character before/after the position of the cursor in the editor? For example, “abcd|efg” where ‘|’ is cursor. How do get ‘d’ (before the cursor) or ‘e’ (after the cursor).

  2. Get the character right before/after the selection. For example, “ab(cde)fg” where “cde” is the current selection. How to returns the character ‘(’ right before and ‘)’ right after it.

Maybe this can be done by the following?

  1. How to get the whole text in the editor?
  2. How to get the cursor position.
  3. How to get the selection position and its length?


Both of your questions have the same answer. If you just have one cursor with a zero-length selection (this is the default state when you left-click inside a document), you can find the character to the left of it using atom.workspace.getActiveTextEditor().selectLeft(). If you have selected characters, the exact same functions do the exact same thing, so the only thing you need to do to tell the difference is to first use atom.workspace.getActiveTextEditor().getSelections() to identify how many Selections you have and whether they contain characters.