Skip to content

Instantly share code, notes, and snippets.

@dtao
Created May 25, 2012 16:10
Show Gist options
  • Save dtao/2788978 to your computer and use it in GitHub Desktop.
Save dtao/2788978 to your computer and use it in GitHub Desktop.
Sublime Text plugin to increment/decrement all selected numbers
import sublime
import sublime_plugin
class NumberCommand(sublime_plugin.TextCommand):
def run(self, edit):
selection = self.view.sel()
for region in selection:
try:
value = int(self.view.substr(region))
self.view.replace(edit, region, str(self.op(value)))
except ValueError:
pass
def is_enabled(self):
return len(self.view.sel()) > 0
class IncrementCommand(NumberCommand):
def op(self, value):
return value + 1
class DecrementCommand(NumberCommand):
def op(self, value):
return value - 1
@dev-gnsairam
Copy link

I've improved this a bit by allowing it to operate when nothing is selected. It does so by detecting number boundaries to the left and to the right of the cursor. E.g. (| = cursor position):
|39px (nothing is selected -> increment: 40, 41, ..., decrement: 38, 37, ...)
39|px ("9" is selected -> increment: 310, 311, decrement: 38, 37, ...)

import sublime
import sublime_plugin

class NumberCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        selection = self.view.sel()
        for region in selection:
            try:
                # Try to operate on around the cursor if nothing is selected
                if region.empty():
                    begin = region.begin()
                    while begin >= 0:
                        if not self.view.substr(begin - 1).isdigit():
                            break
                        begin = begin - 1
                    end = region.end()
                    while end < self.view.size():
                        if not self.view.substr(end).isdigit():
                            break
                        end = end + 1
                    region = sublime.Region(begin, end)

                value = int(self.view.substr(region))
                self.view.replace(edit, region, str(self.op(value)))
            except ValueError:
                pass

    def is_enabled(self):
        return len(self.view.sel()) > 0

class IncrementCommand(NumberCommand):
    def op(self, value):
          return value + 1

class DecrementCommand(NumberCommand):
    def op(self, value):
          return value - 1

Hey buddy, thanks for this code, i am a beginner kindly please tell me how i can use this code...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment