It’s been a long time since I’ve written anything in Perl. Tonight, I wrote a simple C# syntax coloring app, that converts C# source code into syntax-colored HTML. As this is the second Perl program that I can recall ever writing, suggestions for improvements would be more than welcome. Here’s the Perl script that makes it all happen:
$DoubleQuotedString = qr/
(
" # Start of string
(
\\. # Ignore any escaped characters
|
[^"\\] # But not "\
)*
" # End of string
)
/x;
#" hack required for syntax hilighting in TextPad.
$CSharpQuotedString = qr/
@
(
"
(
"" # Ignore ""
|
(^""")* # But not """
)*
"
)
/x;
#"
$EmptyLine = qr/^\s*\Z/;
$CSharpComment = qr/\/\/.*/;
$CSharpKeywords = qr/
\b
(
abstract | as | base | bool | break | byte | case |
catch | char | checked | class | const | continue |
decimal | default | delegate | do | double | else |
enum | event | explicit | extern | false | finally |
fixed | float | for | foreach | goto | if | implicit |
in | int | interface | internal | is | lock | long |
namespace | new | null | object | operator | out |
override | partial | params | private | protected |
public | readonly | ref | return | sbyte | sealed |
short | sizeof | stackalloc | static | string |
struct | switch | this | throw | true | try | typeof |
uint | ulong | unchecked | unsafe | ushort | using |
virtual | volatile | void | where | while | yield
)
\b
/x;
print "<html><head><link rel='stylesheet' href='csharp.css'><\/head><body><div class='code'>\r\n";
@file = <>;
foreach(@file)
{
/(^\s*\/\/.*)/ && do { print "<div class='comment'>$1<\/div>\r\n"; next; };
/\G($EmptyLine)/ && do { print "<div class='line'> <\/div>\r\n"; next; };
print "<div class='line'>";
PARSER:
{
m/\G($CSharpComment)/gc && do { print "<span class='comment'>$1<\/span>"; redo; };
m/\G($DoubleQuotedString)/gc && do { print "<span class='stringliteral'>$1<\/span>"; redo; };
m/\G($CSharpQuotedString)/gc && do { print "<span class='stringliteral'>@$1<\/span>"; redo; };
m/\G($CSharpKeywords)/gc && do { print "<span class='keyword'>$1<\/span>"; redo; };
m/\G\ /gc && do { print " "; redo; };
m/\G(\r)/gc && do { print "\r\n"; redo; };
m/\G(.)/gc && do { print $1; redo; };
print "<\/div>\r\n";
}
}
print "<\/div><\/body><\/html>\r\n";
I use an external CSS stylesheet to define the appropriate formatting for this HTML:
.code
{
font-family: courier new;
font-size: 1em;
}
.comment
{
color: green;
}
.keyword
{
color: blue;
}
.stringliteral
{
color: red;
}
Here’s some sample HTML that was generated:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace Blog
{
public sealed class ThumbnailGenerator
{
private readonly string directory_;
private readonly int width_;
private readonly int height_;
private readonly int border_;
private Bitmap thumbnails_;
private ThumbnailGenerator(string directory, int width, int height, int border)
{
directory_ = directory; // test public
width_ = width;
height_ = height;
border_ = border;
}
public static ThumbnailGenerator CreateThumbnailsFromDirectory(string directory, int width, int height, int border)
{
return new ThumbnailGenerator(directory, width, height, border);
}
public string Directory
{
get { return directory_; }
}
private Bitmap CreateThumbnailBitmap(int thumbnails)
{
return new Bitmap(width_ * thumbnails, height_);
}
private Size GetThumbnailBounds()
{
return new Size(width_ - 2 * border_, height_ - 2 * border_);
}
private RectangleF GetLandscapeThumbnailBounds(Bitmap source, int number)
{
SizeF thumbnailBounds = GetThumbnailBounds();
float width = thumbnailBounds.Width;
float height = thumbnailBounds.Width / source.Width * source.Height;
float x = number * width_ + border_;
float y = border_ + (thumbnailBounds.Height - height) / 2;
return new RectangleF(x, y, width, height);
}
private RectangleF GetPortraitThumbnailBounds(Bitmap source, int number)
{
SizeF thumbnailBounds = GetThumbnailBounds();
float width = thumbnailBounds.Height / source.Height * source.Width;
float height = thumbnailBounds.Height;
float x = number * width_ + border_ + (thumbnailBounds.Width - width) / 2;
float y = border_;
return new RectangleF(x, y, width, height);
}
private void CreateThumbnail(string path, int number)
{
using (Bitmap source = new Bitmap(path))
{
RectangleF bounds;
if (source.Width > source.Height)
bounds = GetLandscapeThumbnailBounds(source, number);
else
bounds = GetPortraitThumbnailBounds(source, number);
using (Graphics g = Graphics.FromImage(thumbnails_))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(source, bounds);
}
}
}
private ImageCodecInfo GetEncoder(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageDecoders();
for (int i = 0; i < encoders.Length; ++i)
if (encoders[i].MimeType == mimeType)
return encoders[i];
return null;
}
private void Save(string path, int quality)
{
if (thumbnails_ == null)
throw new Exception(“You must resize the public bitmap before you save it.”);
ImageCodecInfo ci = GetEncoder(“image/jpeg”);
if (ci == null)
throw new Exception(“Failed to get JPEG image encoder.”);
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param0 = new EncoderParameter(Encoder.Quality, (long)quality);
thumbnails_.Save(path, ci, parameters);
}
public void Run(string thumbnailFile, int quality)
{
string[] files = System.IO.Directory.GetFiles(Directory, @”*.jpg but “”this is a test”“”);
thumbnails_ = CreateThumbnailBitmap(files.Length);
int imageNumber = 0;
foreach (string file in files)
CreateThumbnail(file, imageNumber++);
Save(thumbnailFile, quality);
}
}
//
// class App
// {
// [STAThread]
// static void Main(string[] args)
// {
// Generator generator = Generator.CreateThumbnailsFromDirectory(@”c:\Dev\Blog\Web\Galleries\Barcelona", 64, 64, 4);
// generator.Run(@”c:\Dev\Blog\Web\Galleries\Barcelona\thumbnails.db”, 80);
// }
// }
}
1 archived reader comment
Dave (2004-02-18)
Hi John,
I have a couple suggestions for your regexps:
$DoubleQuotedString = qr/”(\?.)*?”/; $CSharpQuotedString = qr/@”(“”|.)*?”/;
I believe the semantics of my $DoubleQuotedString are the the same as your version. Both of the above regexps use the reluctant (non-greedy) *? quantifier, which I find make writing regexps easier.
It appears your version of $CSharpQuotedString is incorrect, since it appears you are trying to use ^ for negation of a group: (^”“”), but in this context it matches the beginning of the string. ^ only signifies negation in character sets.
another suggestion is to place the following replacement regexp at the beginning of the foreach loop:
s/ / /g;
this will ensure all spaces are replaced with the entity, which will ensure that comments remain formatted and will also force code to only line break where the source code lines has its line breaks, no matter what size the browser or enclosing html element is.
oh yeah, one other suggestion is to include ‘use English;’ at the top of your script, and then refer to $MATCH instead of $1 for readability.
good luck with the perl …