Created
October 30, 2014 14:56
-
-
Save dbakker/7b1afef181549bffd093 to your computer and use it in GitHub Desktop.
Shorten grep/ag/ack results to look nicer in Vim
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
#!/usr/bin/env python2 | |
# Extracted from the "Vim-Holmes" plugin by Daan Bakker | |
# Example: ag --column function | ./grepsnip.py | |
import fileinput | |
import re | |
import os | |
GUESS_SIZE = 10 | |
COLUMNS = os.environ.get('COLUMNS', 120) | |
SNIP_BEFORE = '... ' | |
SNIP_AFTER = ' ...' | |
REGEX = re.compile(r'([^:]+):(\d+):(\d+):(.*)$') | |
def create_snippet(line, start, end, message_size, message_lead=None): | |
size = end - start | |
if message_lead is None: | |
message_lead = (message_size - size) / 5 | |
orig = line | |
line = re.sub('^\s+', '', line) | |
index = max([0, start - (len(orig) - len(line))]) | |
line = re.sub('\s+$', '', line) | |
if len(line) > message_size and index > message_lead: | |
reduction = min([len(line) - message_size + len(SNIP_BEFORE), index - message_lead]) | |
line = SNIP_BEFORE + line[reduction:] | |
index = index - reduction + len(SNIP_BEFORE) | |
if index < 0: | |
index = 0 | |
if len(line) > message_size: | |
line = line[:message_size - len(SNIP_AFTER)] + SNIP_AFTER | |
return line | |
if __name__ == '__main__': | |
for line in fileinput.input('-'): | |
filename, linenumber, start, content = REGEX.match(line).groups() | |
content = create_snippet(line=content, | |
start=int(start), | |
end=int(start) + GUESS_SIZE, | |
message_size=COLUMNS) | |
print('{}:{}:{}:{}'.format(filename, linenumber, start, content)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment