Skip to content

Instantly share code, notes, and snippets.

@FSX
Created August 9, 2010 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FSX/516243 to your computer and use it in GitHub Desktop.
Save FSX/516243 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Indents and wraps text, but doesn't touch docblocks."""
import re
import hashlib
import textwrap
# A regex for matching triple quoted docblocks (only double quotes)
_docblock_re = re.compile('[\t ]*"{3}.*?"{3}[\t ]*', re.DOTALL)
class WrapIdentText:
# 'ident' must not contain regex. Escaped regex is allowed.
def __init__(self, indent, width):
self.indent = indent
self.w = textwrap.TextWrapper(
width=width,
initial_indent=indent,
subsequent_indent=indent)
def wrap(self, text):
chunk_hashes = []
new_text = []
chunks = _docblock_re.findall(text)
# Loop through matched strings (docblocks), create a hash of the
# docblock, replace the docblock with a hash in the text and save the
# hashes and docblocks in a set/list.
for c in chunks:
ch = hashlib.sha1(c).hexdigest()
chunk_hashes.append((ch, c))
text = text.replace(c, ch)
# Wrap and indent text
for chunk in text.split('\n\n'):
new_text.append('\n'.join(self.w.wrap(chunk.strip())))
new_text = '\n\n'.join(new_text)
# Replace the hashes with the docblocks in the wrapped text
for ch in chunk_hashes:
new_text = re.sub(self.indent + ch[0], ch[1], new_text)
return new_text
if __name__ == '__main__':
text = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam in metus nec neque dignissim feugiat. Duis porta est eget elit elementum suscipit. Vivamus ut mauris lacus, ut hendrerit orci.
Ut fermentum mollis iaculis. Curabitur luctus molestie arcu et imperdiet. Sed sit amet auctor leo. Fusce urna libero, tristique ut laoreet at, blandit pharetra leo. Sed pulvinar, nisl ut tristique scelerisque
"""
Ut vitae metus eu sem viverra adipiscing. Morbi id mattis eros. Aenean lacus
ipsum, porta at posuere quis, convallis eu sem. Aliquam ut egestas tortor. Sed
leo libero, placerat vel porta vel, sollicitudin in purus. Vestibulum ut
"""
Aenean pellentesque ante a diam ultrices imperdiet. Praesent est massa, faucibus vel convallis in, gravida vitae arcu. Pellentesque ut erat ut libero ornare accumsan.
"""Praesent sagittis gravida arcu laoreet laoreet. Nunc fringilla magna non erat imperdiet nec porta nibh semper. Curabitur luctus, erat dignissim tincidunt pretium,
libero arcu condimentum massa, quis vehicula est nunc quis sapien."""
'''
w = WrapIdentText(' ', 80)
print w.wrap(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment