Add a number to each selection in Sublime Text 2,

2019-01-15 23:34发布

问题:

Is there a way to add insert a number that is incremented once per cursor in Sublime Text 2?

Example, with | as the cursor:

Lorem ipsum dolor sit amet, |
vehicula sed, mauris nam eget| 
neque a pede nullam, ducimus adipiscing, 
vestibulum pellentesque pellentesque laoreet faucibus.|

Desired result:

Lorem ipsum dolor sit amet, 1|
vehicula sed, mauris nam eget2| 
neque a pede nullam, ducimus adipiscing, 
vestibulum pellentesque pellentesque laoreet faucibus.3|

Does this functionality exist natively, or is there a plugin providing it?

回答1:

I recommend the plugin Text Pastry. The Number Sequence command is the one you need.

I prefer to use the Insert Nums command:

Text Pastry has a build in support for the Insert Nums syntax by providing three numbers separated by one space:

N M P

N: the start index.

M represents the step size which will be added to the index for each selection.

P must be > 0 and will be used to pad the index with leading zeroes.



回答2:

I think that the only way to achieve what you ask is to create your own plugin.

Tools/New Plugin...:

import sublime_plugin


class IncrementSelectionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        start_value = int(self.view.substr(self.view.sel()[0]))

        counter = 0
        for selection in self.view.sel():
            self.view.insert(edit, selection.begin(), str(start_value + counter))
            counter = counter + 1

        for selection in self.view.sel():
            self.view.erase(edit, selection)

Save it in your User directory. Then add a shortcut to your Key Bindings - User:

{ "keys": ["YOUR_SHORTCUT"], "command": "increment_selection" }

Now you can place the cursors where you need:

Insert the number the counter should start from (in this case 1):

Select the number you typed (shift<—):

Type the shortcut: