# Code highlighting. Neat.

I use quite a bit of code in my documents. Now, you can't exactly copy code from an editor to an HTML page … at least, not if you want formatting to be maintained. Before now, used my standard text editor to convert it to html, and then post-process to remove excess styles and such. This worked, but it's still a little cumbersome.

After some searching, I found GeSHi, a php package that will convert and highlight code for use on the web and it is very customizable as well. Very nice. Before I had even looked into how I could use this, I found out that there is a WP plugin that uses it as well: IG-syntax hiliter. So now I can do this:

Keywords:
void for return int

/* cmt */
// cmt

Strings/characters:
"hello"
'x'

Numbers:
12345, , +12, -12, 01234, 0x12ab34, 0X12AB34,
1.234, 1.2e3, 1.2e-3

/* Affine tilemap demo */
void test_tte_ase()
{
// Base inits
irq_init(NULL);
REG_DISPCNT= DCNT_MODE1 | DCNT_BG2;

// Init affine text for 32x32t bg
tte_init_ase(2, BG_CBB(0) | BG_SBB(28) | BG_AFF_32x32,
0, CLR_YELLOW, 0xFE, NULL, NULL);

// Write something
tte_write("\\{P:120,80}o");
tte_write("\\{P:72,104}Round, round, \\{P:80,112}round we go");

AFF_SRC_EX asx= { 124 << 8, 84 << 8, 120, 80, 0x100, 0x100, 0 };
bg_rotscale_ex(&REG_BG_AFFINE[2], &asx);

// Rotate it
while(1)
{
VBlankIntrWait();
key_poll();

asx.alpha += 0x111;
bg_rotscale_ex(&REG_BG_AFFINE[2], &asx);

if(key_hit(KEY_START))
break;
}
}

That should be C code. And by golly it works :). Now I just have to make something for ARM asm.

There are some caveats to the plugin and geshi, though.

• On the plugin side, it works as an extra filter in the displaying process. However, when writing the code in the post, that'll be standard C, complete with brackets and ampersands and such. So it is vitally important to turn off the visual editor and auto-validating of XHTML. It you don't, there will be trouble when you save the post.
• By default, the plugin uses line numbers (bleh) and a few other extras that clutter the actual code. So I turned those off in the plugin options. However, this wasn't enough for everything. The geshi settings for number parsing and using CSS-classes highlighting are also turned off, and if you want those (and I do), you'll have to make a few changes to the plugin manually. In particular, I needed to add $geshi->enable_classes(true)' and $geshi->set_number_highlighting(true)'.
• The regexp for numbers in geshi is incomplete: it doesn't do hex or floats, for example. In parse_non_string_part() use this instead: [php] $reg= "#\\b((0[xX][0-9A-Fa-f]+)|([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)|([0-9]))\\b#";$stuff_to_parse= preg_replace($reg, "<|/NUM!/>\\1|>",$stuff_to_parse); [/php]

Regexp help courtesy of www.regular-expressions.info.