Sublime Forum

Collapsing multiple cursors to the last location

#1

I am using Cmd-D to select and then edit a bunch of things. Now I’m done with those, and I want to carry on selecting more things further down the document. When I press Esc, the multi-cursors collapse to a single cursor in the original location. I understand why this is the default, but in my situation, I need the cursor at the last selected location so I can carry on with my editing from where I left off.

I’ve tried Shift-Esc, but that doesn’t work. Is there a shortcut or some way to make a shortcut for this?

0 Likes

#2

This is straightforward to do with a plugin:

# User/single_last_selection.py
import sublime
import sublime_plugin


class SingleLastSelectionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        sels = list(view.sel())

        if not sels:
            return

        # Always take the last selection
        last = sels[-1]

        view.sel().clear()
        view.sel().add(sublime.Region(last.a, last.b))

        view.show(view.sel()[0])

I have now demoted single_selection to Shift-Esc:

[
    {
        "keys": ["escape"],
        "command": "single_last_selection",
        "context": [
            {
                "key": "panel_has_focus",
                "operand": false,
                "operator": "equal"
            },
            {
                "key": "overlay_has_focus",
                "operand": false,
                "operator": "equal"
            }
        ]
    },
    {
        "keys": ["shift+escape"],
        "command": "single_selection"
    }
]
3 Likes

#4

I’m having trouble with this key mapping, because it has hijacked the normal Esc behavior in menus. I thought I would be able to resolve this with panel_has_focus = false, and that does work for the e.g. Find Panel. But it hasn’t worked in other places: I can’t dismiss the Go To Anything panel/menu/etc with Esc anymore.

Is there a context I can add to resolve this? I only want my key mapping to supercede the default when focus is in the main editing view.

Edit: Seems like also adding an overlay_has_focus check resolves that. Hopefully I don’t find any other edge cases…

0 Likes

#5

OK, I’ve found one more situation where remapping the Esc key is causing problems. The snippets contextual menu is no longer dismissable with the above keymap. I don’t see any other has_focus contexts, or anything about menu in the available context keys. Any other ideas?

Instead of playing whack-a-mole like this, can I just change the TextCommand to do the default thing if there are no selections, before the return?

0 Likes

#6

Does adding { "key": "num_selections", "operator": "not_equal", "operand": 1 } to the context work? This is what the built in single_selection command uses.

0 Likes

#7

Hey, that works! Incredible, thank you very much!

0 Likes