Sublime Forum

Snippet TM_CURRENT_LINE edit?

#1

Hi

I want to find a way to insert a snippet after some line, e.g I select the variable and I want to insert debug print-out below that variable line.

Something like

for f_name in files:
process(f_name)

so I want to be able to select f_name and insert print(“Fname:{}”.format(fname)) inside for loop. Can it be done via standard sublime-snippet or I have to make a plugin ?

0 Likes

#2

Not possible with snippets.

Use this instead:

import sublime
import sublime_plugin

class TestCommandCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        sel = self.view.sel()
        regions = [reg if not reg.empty() else self.view.word(reg) for reg in sel]
        self.view.add_regions("old_sel", regions)

        # Apply in reverse to not mess up our previously saved regions
        # This is also necessary because we need to change the selection
        for reg in reversed(regions):
            selected_text = self.view.substr(reg)
            if not selected_text:
                continue
            text = ('\nprint("%s: {}".format(%s))'
                    % (selected_text.replace('\\', '\\\\').replace('"', '\\"'),
                       selected_text)
                    )
            # view.insert does not auto-indent, so we run the insert command
            # self.view.insert(edit, line.end(), text)
            sel.clear()
            line = self.view.line(reg)
            sel.add(sublime.Region(line.end(), line.end()))
            self.view.run_command('insert', {'characters': text})

        # Restore old selection (additionally, the expanded selection
        # if a selection was empty before)
        sel.clear()
        sel.add_all(self.view.get_regions("old_sel"))
        self.view.erase_regions("old_sel")

Works on multiple selections and auto-expands to the word the caret is under if selection is empty.

0 Likes

#3

Hi

Great, it’s working :smile: Thanks :smile:

For everyone other, to use this you have to setup it for keybind, add something like that to User sublime-keymap (Preferences -> Key Bindings User)

{ "keys": "alt+;"], "command": "test_command", "args": {} },

0 Likes