Created
June 4, 2014 21:11
-
-
Save ShawnMilo/477527d073a7a95bf5f1 to your computer and use it in GitHub Desktop.
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
""" | |
Clean up unnecessary whitespace in a file. | |
Also fix tabs-to-spaces. | |
""" | |
# Must be called from within vim; can't run stand-alone. | |
import vim | |
def remove_trailing_spaces(buff): | |
""" | |
Clean up accidental whitespace at the end of lines. | |
""" | |
for (index, _) in enumerate(buff): | |
buff[index] = buff[index].rstrip() | |
def remove_blank_lines(buff): | |
""" | |
Remove blank lines if there is more than one in a row. | |
Allows two lines before a class declaration. | |
""" | |
cleaned = False | |
for (index, line) in enumerate(buff): | |
# If the line isn't blank, skip it; the remainder of | |
# this function only deletes duplicate blank lines. | |
if line.strip(): | |
continue | |
# If it's an extra blank line but before a | |
# class definition, then leave it alone. | |
try: | |
third_line = buff[index + 2] | |
if third_line.strip().startswith('class'): | |
continue | |
except IndexError: | |
pass | |
# Get the next line. If there is no next line, treat | |
# it like a blank line. | |
try: | |
next_line = buff[index + 1].strip() | |
except IndexError: | |
next_line = '' | |
# If this is a duplicate blank line, or a blank line at | |
# the end of a file, then get rid of it. | |
if not next_line.strip(): | |
del buff[index] | |
cleaned = True | |
# Because we re-size the buffer each time we make a change, start | |
# over with a fresh copy of the buffer after each destructive change. | |
if cleaned: | |
remove_blank_lines(buff) | |
def replace_tabs(buff): | |
""" | |
Replace tab characters with four spaces. | |
""" | |
text = '\n'.join(buff) | |
text = text.replace('\t', ' ') | |
buff[:] = text.split('\n') | |
def main(): | |
""" | |
Clean up whitespace! | |
""" | |
remove_blank_lines(vim.current.buffer) | |
remove_trailing_spaces(vim.current.buffer) | |
replace_tabs(vim.current.buffer) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment