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