This is an old revision of the document!


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
 
lines = []
 
# read all lines from stdin, stripping trailing slashes and whitespace
for line in stdin:
  lines.append(line.rstrip().rstrip('\\').rstrip())
 
# determine the maximum line length
line_max = 0
for line in lines:
  line_len = len(line)
  if line_len > line_max:
    line_max = line_len
 
# 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' % line.ljust(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.

Print/export