Search code examples
sublimetext3sublime-text-plugin

Write Sublime Text 3 plugin to prepend text to selected block of text


I am working on a Sublime Text 3 plugin to work with todo.txt todo files, which are flat text files. I am having trouble writing a plugin command that properly works on a selected region. I would like to be able to prepend the date (or an x) to a selection of rows (each row is a task). Here are the rows before the command.

Task one
Task two

Here is the desired output.

2015-05-26 Task one
2015-05-26 Task two

My command gives this output, but only if I use the multicursor. If I select the region (i.e., highlight with a click-and-drag or CTRL-l) then I get jumbled output.

2015-05-262015-05-26  Task one
Task two

Is there a way to operate on a selection that is robust to both multicursor and highlighting?

Here is a portion of my plugin.

import sublime, sublime_plugin, time, re

class DateTaskCommand(sublime_plugin.TextCommand):
    def run(self, edit):

        for selectedRegion in self.view.sel():
            selectedLines = self.view.lines(selectedRegion)
            adjustBy = 0
            for line in selectedLines:
                 insertPoint = line.begin() + adjustBy
                 prefix = [time.strftime('%Y-%m-%d'), '']
                 self.view.insert(edit, insertPoint, ' '.join(prefix))
                 adjustBy += 1

Solution

  • It seems adjustBy is the problem. try setting :

            adjustBy += len(prefix[0]) + 1 
    

    The problem is that the loop does not reset the position of each line between two insert.