blob: 1c78824439a641ab9d9b043ccf817cd9533dcf90 [file] [log] [blame]
John Koleszara46ec162012-03-28 16:41:16 -07001#!/usr/bin/env python
John Koleszara46ec162012-03-28 16:41:16 -07002##
Yaowu Xu9c01aa12016-09-01 14:32:49 -07003## Copyright (c) 2016, Alliance for Open Media. All rights reserved
4##
5## This source code is subject to the terms of the BSD 2 Clause License and
6## the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
7## was not distributed with this source code in the LICENSE file, you can
8## obtain it at www.aomedia.org/license/software. If the Alliance for Open
9## Media Patent License 1.0 was not distributed with this source code in the
10## PATENTS file, you can obtain it at www.aomedia.org/license/patent.
John Koleszara46ec162012-03-28 16:41:16 -070011##
12"""Wraps paragraphs of text, preserving manual formatting
13
14This is like fold(1), but has the special convention of not modifying lines
15that start with whitespace. This allows you to intersperse blocks with
16special formatting, like code blocks, with written prose. The prose will
17be wordwrapped, and the manual formatting will be preserved.
18
19 * This won't handle the case of a bulleted (or ordered) list specially, so
20 manual wrapping must be done.
21
22Occasionally it's useful to put something with explicit formatting that
23doesn't look at all like a block of text inline.
24
25 indicator = has_leading_whitespace(line);
26 if (indicator)
27 preserve_formatting(line);
28
29The intent is that this docstring would make it through the transform
30and still be legible and presented as it is in the source. If additional
31cases are handled, update this doc to describe the effect.
32"""
33
34__author__ = "jkoleszar@google.com"
35import textwrap
36import sys
37
38def wrap(text):
39 if text:
40 return textwrap.fill(text, break_long_words=False) + '\n'
41 return ""
42
43
44def main(fileobj):
45 text = ""
46 output = ""
47 while True:
48 line = fileobj.readline()
49 if not line:
50 break
51
52 if line.lstrip() == line:
53 text += line
54 else:
55 output += wrap(text)
56 text=""
57 output += line
58 output += wrap(text)
59
60 # Replace the file or write to stdout.
61 if fileobj == sys.stdin:
62 fileobj = sys.stdout
63 else:
James Zern00794a92012-03-29 18:13:27 -070064 fileobj.seek(0)
John Koleszara46ec162012-03-28 16:41:16 -070065 fileobj.truncate(0)
66 fileobj.write(output)
67
68if __name__ == "__main__":
69 if len(sys.argv) > 1:
70 main(open(sys.argv[1], "r+"))
71 else:
72 main(sys.stdin)