Sublime Forum

Is there a way to reverse selected text?

#1

Is there a simple way to reverse selected text? For example, I’d like to change abcd to dcba. I’m using build 4175 on a M1 MacBook Pro.

0 Likes

#2

If you know how to create and use a custom command, that’s a fairly easy task. But I am too lazy to introduce “how”, so I only provides the command implementation.

reverse_selected_text_command.py (filename doesn’t matter)

import sublime
import sublime_plugin


class ReverseSelectedTextCommand(sublime_plugin.TextCommand):
    def run(self, edit: sublime.Edit) -> None:
        for region in self.view.sel():
            if region.empty():
                continue
            text = self.view.substr(region)
            self.view.replace(edit, region, text[::-1])
0 Likes

#3

You can also use the arithmetic command with a parameter of s[::-1].

5 Likes

#4

Thanks for your response! I’m kind of a newbie, but figured I’d try:
Tools → Developer → New Plugin…
A new window came up into which I copied and pasted your program. I saved it as:
Users/mick/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/ReverseText.py
but then I couldn’t figure out how to use the command from within Sublime Text :frowning:

0 Likes

#5

Hi bschaaf. I fear I’m just too much of a newbie to understand your no doubt helpful response. I searched the menus (including looking for “arithmetic” in the Help menu) but couldn’t find that command. Either way, s[::1] is something I’d likely never remember the next time I need it. I’d prefer something like a command that I could intuitively name and then just browse for it in some menu (or ideally find it in the Help menu).

0 Likes

#6

haha always forget arithmetic

0 Likes

#7

Could somebody please help me across the finish line with this? I don’t know how to make use of the script now that I’ve created it.

0 Likes

#8

You can save this file as ReverseSelectedTextCommand.py and add the corresponding keyboard shortcut. I have my own memory rules of thumb to remember the thousands of them I already have among Alfred, SublimeText and others, so change it for yours:

    ,{ "keys": ["super+alt+ctrl+shift+left"], "command": "reverse_selected_text"}

I prefer to put the comma before the opening { so it is safer to delete lines and see them…

0 Likes

#9

Fwiw, ST’s settings file can have trailing commas and comments.

1 Like