Created
May 6, 2018 23:08
-
-
Save hedenface/ddcc11a3b360f4f2a6ce3e81ebb2bb9b to your computer and use it in GitHub Desktop.
SublimeText3 Equal-sign Aligner Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# put in ~/.config/sublime-text-3/Packages/User/EqualizerCommand.py | |
# | |
# I use the following keybindings (Preferences > Key-Bindings > ('User' bindings - on the right side)): | |
# | |
# { | |
# "keys": ["ctrl+shift+e"], | |
# "command": "equalizer" | |
# } | |
# | |
# Given a selection of text in the edit view, it will align all of the right-most | |
# equal signs with whichever of the right-most equal signs in the block of selected | |
# text is the farthest. | |
# Example: | |
# Say you selected the following text: | |
# ``` | |
# $arr = array( | |
# 'key1' => 'val1', | |
# 'some_really_long_key_name' => 'val2', | |
# 'key3' => 'val3', | |
# ); | |
# ``` | |
# And then pressed ctrl+shift+e, that block of code would turn into: | |
# ``` | |
# $arr = array( | |
# 'key1' => 'val1', | |
# 'some_really_long_key_name' => 'val2', | |
# 'key3' => 'val3', | |
# ); | |
# ``` | |
# I find it useful for keeping blocks of variable initializers, etc. clean | |
import sublime, sublime_plugin | |
class EqualizerCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
for region in self.view.sel(): | |
if not region.empty(): | |
# Get the selected text | |
s = self.view.substr(region) | |
lines = s.split('\n') | |
equalized = '' | |
# Get the right most equal sign in the lines | |
max_equal_pos = 0 | |
for line in lines: | |
equal_pos = line.rfind('=') | |
if equal_pos > max_equal_pos: | |
max_equal_pos = equal_pos | |
# loop through the lines and adjust each one | |
for line in lines: | |
equal_pos = line.rfind('=') | |
if equal_pos >= max_equal_pos or equal_pos <= 0: | |
equalized += line + '\n' | |
continue | |
line_parts = line.rsplit('=', 1) | |
lhs = line_parts[0].rstrip() | |
rhs = line_parts[1] | |
equalized += lhs.ljust(max_equal_pos) + '=' + rhs + '\n' | |
self.view.replace(edit, region, equalized) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment