Skip to content

Instantly share code, notes, and snippets.

@patcorwin
Forked from andytill/IntroduceVariableCommand.py
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patcorwin/e9883ee5ddce1bda0c09 to your computer and use it in GitHub Desktop.
Save patcorwin/e9883ee5ddce1bda0c09 to your computer and use it in GitHub Desktop.
import sublime
import sublime_plugin
import re
class IntroduceVariableCommand(sublime_plugin.TextCommand):
var_name = "NewVar"
def run(self, edit):
sels = self.view.sel()
for sel in sels:
if not sel.empty():
self.introduce_variable(edit, sel)
def introduce_variable(self, edit, sel):
sel_text = self.view.substr(sel)
top_line = self.view.lines(sel)[0]
top_line_text = self.view.substr(top_line)
indentation = ""
match = re.search(r"\W*", top_line_text, re.UNICODE)
if match:
indentation = match.group(0)
var_declaration = indentation + self.var_name + " = " + sel_text + ",\n"
self.view.replace(edit, sel, self.var_name)
self.view.insert(edit, top_line.a, var_declaration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment