Escaping and Formatting Newlines

Using the “Send Selection to Command” feature of Geany and a simple Python script, you can re-format escaped newlines in your code so that the trailing back-slash always is aligned.

To demonstrate, here is a before and after the operation:

/* Some un-aligned, misplaced and missing escaped newlines */
#define FOO_BAR(a, b)
do
{
  if (a < b) \
    call_c(b, a);
  else \
    call_c(a, b);
}
while (0)\

/* After selecting the whole chunk of code and sending it through the Python script */
#define FOO_BAR(a, b) \
do                    \
{                     \
  if (a < b)          \
    call_c(b, a);     \
  else                \
    call_c(a, b);     \
}                     \
while (0)

This is a simple Python script to do this:

#!/usr/bin/env python
 
from sys import stdin, stdout
 
 
# 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
lines = [l.rstrip(' \t\r\n\v\\') for l in stdin]
 
# determine the maximum line length
line_max = max([line_width(l) for l in lines])
 
# write out the formatted lines to stdout
num_lines = len(lines)
for i, line in enumerate(lines):
    if i != num_lines - 1:
        stdout.write('%s\\\n' % ljust(line, line_max))
    else:
        stdout.write('%s\n' % line)

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 the user manual for more information about sending text through custom commands.