Version 13 of HOW TO - Splice lines of source code

Updated 2010-11-01 18:20:01 by tomk

While working on a tcl implementation of a cpp (i.e. C preprocessor) I found it necessary to splice together lines with escaped new lines while preserving the line number where the splice began.

Given a file of source lines that look like the following.

line(1)
line(2)\
line(3) with space after escape\    
line(4)\
line(5)
line(6)\
line(7)
line(8)

This code ...

set fid [open [file normalize "./filename"] r]
set text [read ${fid}]
close $fid
regsub -all -- {[\\][ \t]*[\n]} ${text} "\\\n" text
while { [regsub -all -- {[\\][\n](.*?[^\\])[\n]} ${text} "\\1\n\n" text] } {}

...produces the following results.

lineoutput
1line(1)
2line(2)line(3) with space after excapeline(4)line(5)
3
4
5
6line(6)line(7)
7
8line(8)

Notice that the lines have been spliced together and the spliced lines occur on the correct line in the output. Also notice that line 3, which has white space after the backslash, was spliced. This is the way cpp behaves when joining lines.

Tom Krehbiel