Search code examples
sublimetext2sublimetextsublime-text-plugin

ROT47 of the current selection in SublimeText


When doing CTRL+SHIFT+P, there is command named Rot13 selection which allows to encrpyt the selected text.

I'd like to add a command named Rot47 selection that does:

selection = 'Test'
print ''.join(chr(33 + ((ord(ch) + 14) % 94)) for ch in selection)
#Output: %6DE

Where to write this Python code in SublimeText to have this new command present in CTRL+SHIFT+P?


Solution

  • You can write a plugin.

    Some beginner (and not 100% correct) code is available here.

    A complete plugin for Rot47 would have the following code:

    import sublime, sublime_plugin
    
    class Rot47Command(sublime_plugin.TextCommand):
        def run(self, edit):
            for region in self.view.sel():
                if not region.empty():
                    s = self.view.substr(region)
                    s = ''.join(chr(33 + ((ord(ch) + 14) % 94)) for ch in s)
                    self.view.replace(edit, region, s)
    

    Where to write this code?

    Tools > New Plugin... will open a new buffer with some boilerplate code. Replace the boilerplate with the above code and save the file as rot47.py in /<sublime-text-dir>/Packages/User/.

    You can test the above plugin by opening the console using Ctrl+`, and typing view.run_command('rot47') and hitting Enter. Make sure that you've selected some text before running your new Rot47 command.

    Furthermore, if you want to create a keyboard shortcut for your new rot47 command: go to Preferences > Key Bindings -- User and add the following entry:

    { "keys": ["ctrl+shift+4"], "command": "rot47" }
    

    (you can of course choose a more meaningful key combination.)

    What did the above plugin code do?

    self.view.sel() gives an iterable on the selected text regions (there can be multiple selections in the same buffer, go Sublime!). A region is basically a (start_index, end_index) pair that denotes a selected substring. self.view.substr(region) gives you the required substring.

    We then modify the selection text (variable s) as desired and replace the selection with the new text (the call to self.view.replace()).

    For a more extensive API reference, see this.