Sublime Forum

Looping and replacing lines

#1

I am trying to loop over a selection, grab the entire line and then replace the line with new text if a condition is met. I have figured out how to loop over the selected regions, grab each line, but I can’t figure out how to replace the line with new text.

Here is the code I have so far:

class TestingCommand(sublime_plugin.TextCommand):
    def run(self, edit):
            # Get a reference to the selections
            sel = self.view.sel()
            # Loop over the various selections
            for region in self.view.sel():
                # grab full lines regardless of where they start in the line
                line2 = self.view.line(region)
                # split them into individual lines
                lines = self.view.split_by_newlines(line2)
                for l in lines:
                    # return the contents as a string
                    s = self.view.substr(l)
                    print(s)

Where the print statement is, I would like to replace the entire line. Loop and repeat. Not all lines would be changed or replaced.

Thanks for any help or direction.

0 Likes

#2

Have you tried view.replace?

0 Likes

#3

In addition to replace, be sure you start from the end of the list when doing your replace as to not mess up the positions stored by view.sel()

0 Likes

#4

Thanks for the hint of starting backwards. I couldn’t figure out how to not affect the positions.

Before I came across your hint I tried a different approach. I grabbed the line numbers of the selection, erased the contents of a line and then inserted the new content for the line and then moved to the new line. Code below:

class DemotetCommand(sublime_plugin.TextCommand): def run(self, edit): ss = sublime.load_settings("Preferences.sublime-settings") ts = ss.get("tab_size",1) view = self.view sel = view.sel() line_nums = [view.rowcol(line.a)[0] for line in view.lines(sel[0])] for row in line_nums: pt = view.text_point(row, 0) line = view.line(pt) s = self.view.substr(line) s2 = s s =s.lstrip() if len(s) > 0: # check if the first character is a slash if s[0] == '\\': if int(s[1]) < 4: new_num = (int(s[1])+1) new_nums = str(new_num) self.view.erase(edit, sublime.Region(pt + len(s2),pt)) self.view.insert(edit, pt, ' '*new_num*ts + s) self.view.replace(edit, sublime.Region(pt+new_num*ts+1, pt+new_num*ts+2), new_nums)

0 Likes