]> git.phdru.name Git - dotfiles.git/blob - bin/text-wrap.py
Initial import
[dotfiles.git] / bin / text-wrap.py
1 #! /usr/bin/env python
2
3 import sys
4
5
6 def usage(code=0):
7    sys.stderr.write("Usage: %s [-0|--null] [-n|--no-newline] [-s|--space] [-w|--width] [width]\n" % sys.argv[0])
8    sys.exit(code)
9
10
11 def get_args():
12    from getopt import getopt, GetoptError
13
14    try:
15       options, arguments = getopt(sys.argv[1:], "0nsw:",
16          ["null", "no-newline", "space", "width="])
17    except GetoptError:
18       usage(1)
19
20    print0 = False
21    newline = True
22    space = ''
23    width = None
24
25    for option, value in options:
26       if option in ("-h", "--help"):
27          usage()
28       elif option in ("-0", "--null"):
29          print0 = True
30       elif option in ("-n", "--no-newline"):
31          newline = False
32       elif option in ("-s", "--space"):
33          space = u' '
34       elif option in ("-w", "--width"):
35          width = int(value)
36       else:
37          usage(2)
38
39    if arguments:
40       if width is not None:
41          usage(3)
42       elif len(arguments) > 1:
43          usage(4)
44       else:
45          width = int(arguments[0])
46
47    return print0, newline, space, width
48
49 print0, newline, space, width = get_args()
50
51
52 from m_lib.defenc import default_encoding
53 text = sys.stdin.read().decode(default_encoding)
54 if not newline:
55    text = text.rstrip()
56
57 if width:
58    import textwrap
59    text = textwrap.fill(text, width - 2*len(space),
60       initial_indent=space, subsequent_indent=space)
61    if space:
62        text = u'\n'.join([line+space for line in text.split(u'\n')])
63 else:
64    text = u"%s%s%s" % (space, text, space)
65
66 sys.stdout.write(text.encode(default_encoding))
67
68 if print0:
69    sys.stdout.write('\0')
70 elif newline:
71    print