Sublime Forum

Swap point and mark as in Emacs

#1

In Emacs when one pastes text one can optionally invoke a shortcut key to swap point and mark which puts ones cursor in the position it was before pasting. I would like to replicate this in Sublime.

0 Likes

#2

Not an Emacs user, but does by chance Main Menu > Edit > Mark > Swap with Mark provide this functionality?

0 Likes

#3

That seems to toggle selection? Am I right? I am looking for the swapping of the cursor position to take place without worrying about the region per se. I cobbled together this plugin (with the help if AI):

import sublime
import sublime_plugin

# Global variables to store the last pasted region and toggle state
last_paste_region = None
toggle_state = False

class PasteAndTrackRegionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        global last_paste_region
        global toggle_state

        # Save the clipboard content
        clipboard_content = sublime.get_clipboard()

        # Get the current selection before pasting
        before_paste_regions = list(self.view.sel())

        # Paste the text
        self.view.run_command("paste")

        # Get the new selection after pasting
        after_paste_regions = list(self.view.sel())

        # Determine the region where the text was pasted
        if before_paste_regions and after_paste_regions:
            start_position = before_paste_regions[0].begin()
            end_position = after_paste_regions[-1].end()
            # Set the last_paste_region to include the area from before paste to after paste
            last_paste_region = sublime.Region(start_position, end_position)
            toggle_state = False  # Reset toggle state
            sublime.status_message("Pasted and tracked region.")

class TogglePointAndMarkCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        global last_paste_region
        global toggle_state

        if last_paste_region:
            self.view.sel().clear()
            if toggle_state:
                # Move cursor to the end of the pasted region
                self.view.sel().add(sublime.Region(last_paste_region.end(), last_paste_region.end()))
                self.view.show(last_paste_region.end())
            else:
                # Move cursor to the start of the pasted region
                self.view.sel().add(sublime.Region(last_paste_region.begin(), last_paste_region.begin()))
                self.view.show(last_paste_region.begin())
            toggle_state = not toggle_state
        else:
            sublime.status_message("No pasted region to jump to.")

This however only works if text is copied and pasted from within Sublime. I have not been able to get it to work with text copied from external apps.

0 Likes