Refactoring Code in Sublime Text 3

Currently I do this with Find All (Cntrl+F old_var, alt+enter new_var), but this replaces words in my comments and strings.

A comment in this answer suggested the PyRefactor plugin which requires rope. These tools seem to have defaults that are too heavy-handed for my purposes. I just want to refactor variable names in stand-alone python scripts with Sublime Text 3.

So in a script like

# Where did my hat go?
hat = 0
print(hat)
print("hat")

The hat variable (not in strings nor comments) can be replaced with something else at the touch of a hotkey. No need for a special project folder/configuration, and nothing changed across multiple files. Unfortunately, Find All hat -> llama does...

# Where did my llama go?
llama = 0
print(llama)
print("llama")

EDIT:

I appreciate @Toto's regex solution, but I'm not fluent in that yet and would like a method that works more consistently and is easier to remember. Is there a plugin (or can I write one?) that identifies all the globally defined and stated variables (arguments in function calls, etc), and allows for a simple Find and Replace?

2

1 Answer

  • Ctrl+H
  • Find: (?:^(?<!#).*\K|(<?!"))\bhat\b(?!")
  • Replace: llama
  • check Regular expression
  • check Whole word
  • check Wrap
  • Replace all

Explanation:

(?: ^ : beginning of line (?<!#) : negative lookbehind, zero-length assertion that makes sure we don't have # before .* : 0 or more any character \k : forget all we have seen until this position | : OR (?<!") : negative lookbehind, zero-length assertion that makes sure we don't have " before
)
\b : word boundary to not match chat, remove it if you want to match chat also
hat : literally
\b : word boundary to not match hats, remove it if you want to match hats also
(?!") : negative lookahead, zero-length assertion that makes sure we don't have " after

Given:

# Where did my hat go?
hat = 0
chat = 0
print(hat)
print("hat")
print(chat)

Result for given example:

# Where did my hat go?
llama = 0
chat = 0
print(llama)
print("hat")
print(chat)

Before:

enter image description hereAfter:

enter image description here

6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like