How would I add a tab to each line from the code selection in the view?
Add a tab to each line in self.view.sel()
AFAIK, there’s no way to execute the find/replace dialog as a command (which would make this easy, and also would make me very happy because I often want to be able to include find/replace in a macro).
You’ll need to ask the view for the lines, and then insert a tab or replace the line with a tab at the beginning. You’ll need to be careful, because as soon as you insert a tab, this will shift the offset for all subsequent lines. Here is some sample code that should do what you want:
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
for r in reversed(self.view.sel()):
for line_r in reversed(self.view.lines(r)):
# Alternatively, use view.insert() here if you're not
# concerned about tabs getting converted to spaces.
text = self.view.substr(line_r)
self.view.replace(edit, line_r, '\t'+text)
An alternative approach is to extract all the line regions into a python list, clear self.view.sel(), and then add them to self.view.sel(). Then iterate over self.view.sel() and call substr/replace or insert(). When you modify regions in a RegionSet, they automatically get adjusted (so you don’t have to do things in reverse). But this would be a bit more complex than the above example.
@sapphirehamster, thanks! I’ll try that.
@adzenith - I don’t want to alter the code - I want to tab the code I’m sending elsewhere via plugin.
Just checked it out but it seems to be also changing the view text as well by adding tabs.
Is there anyway to actually just grab this text ‘tabbed’ without changing the text in view?
I’m not really sure what you mean. In the sample code, you have a variable “text” which contains a line of code. Prepend a tab to it and you now have your indented line. Just don’t call “replace” if you don’t want to update the view. You can append the lines to a list if you need the entire chunk all at once.