Skip to content

Instantly share code, notes, and snippets.

@lrhn
Last active June 25, 2016 21:41
Show Gist options
  • Save lrhn/0ad093c8bd84e653b3e0 to your computer and use it in GitHub Desktop.
Save lrhn/0ad093c8bd84e653b3e0 to your computer and use it in GitHub Desktop.
Sublime plugin for incrementing and decrementing numbers in selections.
import sublime, sublime_plugin, re
def updateSelection(command, edit, delta, preserveLength):
rd = re.compile(r'\d+')
value = -delta
originalLength = 1
if (delta < 0):
value = len(command.view.sel()) * -delta
selCountLength = 1;
selectionCount = len(command.view.sel())
while selectionCount > 10:
selectionCount /= 10
selCountLength += 1
for selection in command.view.sel():
selectionText = command.view.substr(selection);
matches = list(rd.finditer(selectionText))
if (len(matches) > 0):
for match in reversed(matches):
matchText = match.group(0)
originalLength = len(matchText)
value = int(matchText) + delta
if value < 0:
value = 0
valueText = str(value)
if (preserveLength):
valueText = valueText.zfill(originalLength)
selectionText = (selectionText[:match.start(0)] +
valueText +
selectionText[match.end(0):])
command.view.replace(edit, selection, selectionText)
else:
# insert a number that is previous value+delta at end of selection.
value += delta
if value < 0:
value = 0
valueText = str(value)
if preserveLength:
valueText = valueText.zfill(max(originalLength, selCountLength))
command.view.replace(edit, selection, selectionText + valueText)
class IncrementSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, 1, False)
class DecrementSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, -1, False)
class IncrementSelectionPreserveLengthCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, 1, True)
class DecrementSelectionPreserveLengthCommand(sublime_plugin.TextCommand):
def run(self, edit):
updateSelection(self, edit, -1, True)
# Add to User keymap:
# { "keys": ["ctrl+keypad_plus"], "command": "increment_selection" },
# { "keys": ["ctrl+keypad_minus"], "command": "decrement_selection" },
# { "keys": ["shift+ctrl+keypad_plus"],
# "command": "increment_selection_preserve_length" },
# { "keys": ["shift+ctrl+keypad_minus"],
# "command": "decrement_selection_preserve_length" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment