Last active
January 3, 2016 12:49
-
-
Save jeddenlea/8465224 to your computer and use it in GitHub Desktop.
Simple little script to aid formatting of comments 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 python | |
""" | |
Select some text and then "!fmtcomment". It understands "//" and | |
"#" comments, works with indenting in spaces and tabs. It assumes | |
you want to squeeze your text within 80-chars, and treats tabs as | |
4 spaces thusly. | |
E.g., will turn | |
// Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. | |
// Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. | |
// | |
// Duis aute irure dolor | |
// in reprehenderit in voluptate velit esse | |
// cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt | |
// in culpa qui officia deserunt mollit anim id est laborum. | |
... into... | |
// Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
// tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
// quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
// consequat. | |
// | |
// Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore | |
// eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, | |
// sunt in culpa qui officia deserunt mollit anim id est laborum. | |
""" | |
import re | |
import sys | |
lines = sys.stdin.readlines() | |
if len(lines) < 1: | |
print >>sys.stderr, "Line!" | |
sys.exit(1) | |
s = lines[0].rstrip() | |
m = re.match(r"^\s*(?:#|//)", s) | |
if not m: | |
print >>sys.stderr, "No comment." | |
sys.exit(1) | |
comment = m.group() | |
words = [] | |
for line in lines: | |
sub_words = line.split() | |
if len(sub_words) > 0 and sub_words[0] in ("#", "//"): | |
sub_words = sub_words[1:] | |
if len(sub_words) == 0: | |
words.append("\n") | |
else: | |
words.extend(sub_words) | |
while words: | |
firstword = words.pop(0) | |
if firstword == "\n": | |
print comment | |
continue | |
out = comment + " " + firstword | |
while words: | |
if words[0] == "\n": | |
break | |
if len(out.expandtabs(4)) + 1 + len(words[0]) <= 80: | |
out += " " + words.pop(0) | |
else: | |
break | |
print out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gqap