9

In Sublime Text (using Sublime Text 3), you can get out of a multiple selection / multiple caret mode by pressing the Esc key. When you do this, only the first selection / caret will remain.

Is there a way to make it so that only the last selection / caret will remain instead?

I often find myself hitting escape then needing to move my cursor to what used to be the last selection.

Use case:

I type this using multiple selection:

int foo(
  int x,
  int x,
  int x,
  int x,
)

and I want to get rid of the last comma to get to:

int foo(
  int x,
  int x,
  int x,
  int x
)

I'd like to hit the Esc key and have my caret be right after that last int x,.

ericcodes
  • 93
  • 4

1 Answers1

9

I think this is not a default command in sublime text. However you can easily create this behavior on your own. Just press Tools >> New Plugin... and paste the following:

import sublime_plugin


class SingleLastSelectionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        if len(view.sel()):
            last = view.sel()[-1]
            view.sel().clear()
            view.sel().add(last)

Afterwards create a keybinding:

{ "keys": ["escape"], "command": "single_last_selection", "context":
    [
        { "key": "num_selections", "operator": "not_equal", "operand": 1 }
    ]
},

It might be necessary to copy all escape keybinding from the default keymap to keep the action precedence (hide autocompletion before removing multiple cursors and so on).

r-stein
  • 461
  • 2
  • 5
  • 1
    Super cool! I've been wanting this for ages never bothered to really search for it. I use `shift+escape` to still keep the other `escape` functionality. – freeall Oct 11 '17 at 09:01
  • This Fails when the multiple selection is from DOWN -> UP --- **Example:** Say the first occurrence is on _line 204_ and the second occurrence of same word/phrase is say on _line 52_, now when you first select the word/phrase on _line 204_ (1st selection) and then hit `Ctrl+D` word/phrase on _line 52_ is selected (2nd selection) but now when you hit `Shift + Esc`, the cursor jumps back to first selection _line 204_ and does not remain on the last selection _line 52_ (last selection) --- **Is it possible to modify the script to solve this ???** – b Tech Jan 30 '22 at 07:04
  • @bTech I guess they are sorted by appearance, but you can work around this by pressing esc when you reach the top of the file and continue. – agiopnl Jul 20 '23 at 01:54