1#!/usr/bin/env python 2## Copyright (c) 2012 The WebM project authors. All Rights Reserved. 3## 4## Use of this source code is governed by a BSD-style license 5## that can be found in the LICENSE file in the root of the source 6## tree. An additional intellectual property rights grant can be found 7## in the file PATENTS. All contributing project authors may 8## be found in the AUTHORS file in the root of the source tree. 9## 10"""Wraps paragraphs of text, preserving manual formatting 11 12This is like fold(1), but has the special convention of not modifying lines 13that start with whitespace. This allows you to intersperse blocks with 14special formatting, like code blocks, with written prose. The prose will 15be wordwrapped, and the manual formatting will be preserved. 16 17 * This won't handle the case of a bulleted (or ordered) list specially, so 18 manual wrapping must be done. 19 20Occasionally it's useful to put something with explicit formatting that 21doesn't look at all like a block of text inline. 22 23 indicator = has_leading_whitespace(line); 24 if (indicator) 25 preserve_formatting(line); 26 27The intent is that this docstring would make it through the transform 28and still be legible and presented as it is in the source. If additional 29cases are handled, update this doc to describe the effect. 30""" 31 32__author__ = "jkoleszar@google.com" 33import textwrap 34import sys 35 36def wrap(text): 37 if text: 38 return textwrap.fill(text, break_long_words=False) + '\n' 39 return "" 40 41 42def main(fileobj): 43 text = "" 44 output = "" 45 while True: 46 line = fileobj.readline() 47 if not line: 48 break 49 50 if line.lstrip() == line: 51 text += line 52 else: 53 output += wrap(text) 54 text="" 55 output += line 56 output += wrap(text) 57 58 # Replace the file or write to stdout. 59 if fileobj == sys.stdin: 60 fileobj = sys.stdout 61 else: 62 fileobj.seek(0) 63 fileobj.truncate(0) 64 fileobj.write(output) 65 66if __name__ == "__main__": 67 if len(sys.argv) > 1: 68 main(open(sys.argv[1], "r+")) 69 else: 70 main(sys.stdin) 71