Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
howtos:format_escaped_newlines [2013/04/21 13:05] – Create page codebrainz | howtos:format_escaped_newlines [2013/08/23 10:32] (current) – Improve script to handle tabs (assumes 8space wide, would need a way to get this from Geany) colombanw | ||
---|---|---|---|
Line 36: | Line 36: | ||
from sys import stdin, stdout | from sys import stdin, stdout | ||
- | lines = [] | + | |
+ | # computes the width of a line, taking tabs into account | ||
+ | def line_width(line, | ||
+ | length = 0 | ||
+ | for c in line: | ||
+ | if c == ' | ||
+ | length += tab_width - (length % tab_width) | ||
+ | else: | ||
+ | length += 1 | ||
+ | return length | ||
+ | |||
+ | |||
+ | # pads @string with @char to become @width wide | ||
+ | # at least one @char will be added | ||
+ | def ljust(string, | ||
+ | while True: | ||
+ | string += char | ||
+ | if line_width(string, | ||
+ | break | ||
+ | return string | ||
# read all lines from stdin, stripping trailing slashes and whitespace | # read all lines from stdin, stripping trailing slashes and whitespace | ||
- | for line in stdin: | + | lines = [l.rstrip(' |
- | | + | |
# determine the maximum line length | # determine the maximum line length | ||
- | line_max = 0 | + | line_max = max([line_width(l) |
- | for line in lines: | + | |
- | line_len = len(line) | + | |
- | if line_len > line_max: | + | |
- | line_max = line_len | + | |
# write out the formatted lines to stdout | # write out the formatted lines to stdout | ||
num_lines = len(lines) | num_lines = len(lines) | ||
for i, line in enumerate(lines): | for i, line in enumerate(lines): | ||
- | | + | |
- | stdout.write(' | + | stdout.write(' |
- | else: | + | else: |
- | stdout.write(' | + | stdout.write(' |
</ | </ | ||
Save it to a file, make it executable and then use Edit-> | Save it to a file, make it executable and then use Edit-> | ||
+ | |||
+ | {{tag> |