For the TextMate users out there who write C and C++, here’s a handy command for beautifying a bunch of #define lines. I don’t know about you, but I’m used to seeing lots of header files with this kind of junk:
#define FOO 1
#define BAR 3
#define BAZ (FOO + BAR)
#define REALLY_LONG_DEFINE (BAZ * 2)
What I want is a magic command to line up all the definitions to the column that’s the nearest multiple of the tab size, like so:
#define FOO 1
#define BAR 3
#define BAZ (FOO + BAR)
#define REALLY_LONG_DEFINE (BAZ * 2)
So here’s a script to do that: Download “Reformat Defines” TextMate Command. Source code follows for the curious.
Source Code
#!/usr/bin/ruby
lines = Array.new
# Read in lines
STDIN.readlines.each do |line|
match = line.strip.match(/#define (\S+)\s+(.*)/)
if (match)
lines << { :constant => match[1], :value => match[2] }
else
lines << line.rstrip
end
end
# Find longest constant
constant_size = 0;
lines.each do |line|
if (line.class == Hash && line[:constant].length > constant_size)
constant_size = line[:constant].length
end
end
# Up size to next multiple of the tab size:
tab_size = ENV['TM_TAB_SIZE'].to_i
constant_size = constant_size + (tab_size - (constant_size % tab_size))
# Format output
lines.each do |line|
if (line.class == Hash)
printf("#define %-#{constant_size}s%s\n", line[:constant], line[:value])
else
puts line
end
end