PDA

View Full Version : syntax highlighting for code examples


brothercake
05-12-2003, 09:24 PM
I started writing one, that does stuff like this:

<?php
$pre_code = <<<here
<pre>
//lullaby iterator
while(sleep != 'zzz')
{
sheep++;
}
</pre>
here;
require ("inc/process/precode_parser.inc");
?>

So that I can syntax-highlight javascript examples:

<?php

//comments
$pre_code = preg_replace("/(\/\/.*)\n/","<em class=\"codeComment\">$1</em>",$pre_code);

//reserved words
$pre_code = preg_replace("/(while|if|else|for|return|new|null)/","<span class=\"codeReserved\">$1</span>",$pre_code);

//brackets and braces
$pre_code = preg_replace("/([\(\)\{\}])/","<span class=\"codeBracket\">$1</span>",$pre_code);

//strings
$pre_code = preg_replace("/('[^']+')/","<span class=\"codeString\">$1</span>",$pre_code);

//output result
echo ($pre_code);

?>

But before I sit here adding all the right reserved words ... checking things like not to highlight reserved words if they're used conversationally in comments ...

... I wondered - has anyone else already done this? save me the hassle ;)

missing-score
05-12-2003, 09:35 PM
Im afraid I dont know of anyone who has done this.

However :D

If you manage to do this, would you be willing to contribute to our futuremb (http://www.futuremb.co.uk) project. Ofcoure we would be willing to put you in credits!

mordred
05-13-2003, 08:51 PM
*raises hand*

I have tinkered with a JavaScript syntax highlighing machine built in PHP some months ago. What started as a small script grew into some class files and a semi-functional parser. Regular expressions alone are fine, but they are quite bad when it comes to context. For instance, the keyword "new" could be part of a comment, a string or a regular expression. Or of a variable/object name.
So this all gets more and more complicated... I thought about writing a real parser in PHP, but until now that's nothing more than an idea which needs plenty of free time. Right now it's unfinished and contains a lot of hacks, nearly Beta stage.

Anyway, on this page you can see a live demo:
http://www.trollscript.de/jssyntax/index.php

There's also a link to download the files involved. Any feedback/patches/suggestions are highly welcome. :)

bored
05-16-2003, 07:41 AM
I think I found this on the php site. Works nice, even has line numbers.


<?

if(!empty($_REQUEST["noline"])){
$noline = true;
}

ob_start();
show_source ("file.php" );

$raw = ob_get_contents();

ob_end_clean();

$raw = explode ("<br />", $raw);
$ml = strlen(count($raw));

for($i = 0;$i < count($raw);$i++){

if (!isset($noline )){
$gap = ($ml - strlen( i));
$raw[$i] = "<FONT COLOR=#999999><CODE>["
.str_repeat(" ", $gap)
.$i
."]</CODE></FONT>"
.$raw[$i] . "<BR />";

}else{
$raw[$i] = "$raw[$i]<BR />";
}

}

$raw = implode ("",$raw);

echo "<html>\n <body>\n$raw\n </body>\n</html>";

?>