Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
howtos:format_escaped_newlines [2013/04/21 13:05] – Create page codebrainzhowtos: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, tab_width=8): 
 +    length = 0 
 +    for c in line: 
 +        if c == '\t': 
 +            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, width, char=' ', tab_width=8): 
 +    while True: 
 +        string += char 
 +        if line_width(string, tab_width) > width: 
 +            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(' \t\r\n\v\\'for l in stdin]
-  lines.append(line.rstrip().rstrip('\\').rstrip())+
  
 # determine the maximum line length # determine the maximum line length
-line_max = +line_max = max([line_width(l) for in lines])
-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):
-  if i != num_lines - 1: +    if i != num_lines - 1: 
-    stdout.write('%s \\\n' % line.ljust(line_max)) +        stdout.write('%s\\\n' % ljust(line, line_max)) 
-  else: +    else: 
-    stdout.write('%s\n' % line)+        stdout.write('%s\n' % line) 
 </code> </code>
  
 Save it to a file, make it executable and then use Edit->Format->Send Selection to->Set Custom Commands to add it to the commands. See [[http://www.geany.org/manual/current/index.html#sending-text-through-custom-commands|the user manual]] for more information about sending text through custom commands. Save it to a file, make it executable and then use Edit->Format->Send Selection to->Set Custom Commands to add it to the commands. See [[http://www.geany.org/manual/current/index.html#sending-text-through-custom-commands|the user manual]] for more information about sending text through custom commands.
 +
 +{{tag>howto escaped newlines custom commands}}
Print/export