I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

January 02, 2005

Client-Side code highlighting

When I visited Alex Gorbatchev's blog, I noticed he had a unique client-side code highlighting solution in place, one I hadn't seen anywhere else. That's something I've wanted on my blog for a while; the vanilla <PRE> sections I've been using are servicable, but primitive. Although I loves me some regex, I don't know squat about PERL so I've been hesitant to hack anything fancier into my Movable Type install.

After I asked Alex about his solution, he was nice enough to package up his JavaScript syntax highlighter as dp.SyntaxHighlighter. It's really quite slick, and it works with all kinds of code: C#, VB.NET, JavaScript, PHP, SQL, and XML. Here's a VB.NET sample:

    Public Function GetGoogleWordFrequency(ByVal strWord As String) As Integer
        Dim strUrl As String = "http://www.google.com/search?num=1&q=" & _
          Web.HttpUtility.UrlEncode(strWord)
        Dim wc As New WebClientGzip
        Dim strPageContents As String = wc.DownloadDataGzip(strUrl)
        Dim m As Match
        m = Regex.Match(strPageContents, _
          "results.*?\d+.*?\d+.*?of about.*?(?<TotalResults>[\d,]+)", _
          RegexOptions.IgnoreCase)
        If Not m Is Nothing Then
            Dim strResults As String = m.Groups("TotalResults").ToString
            If strResults.Length > 0 Then
                Return Convert.ToInt32(strResults.Replace(",", ""))
            End If
        End If
        Return -1
    End Function

Alex tested this JavaScript on FireFox and IE6, and is looking for compatibility feedback on other browsers.

Posted by Jeff Atwood    View blog reactions

 

« 2005: Twenty years of Windows On mistakes »

 

Comments

Alex and I are currently.. uh.. wrangling with the fact that there isn't an .innerText property on elements in Mozilla/Firefix.

There is an .innerHTML property, but there are some bizarre ramifications when the "HTML" has escaped markup inside of it. It's more subtle (buggy?) than you might think.

More details in the comments at his blog:

http://blog.dreamprojections.com/archive/2005/01/01/461.aspx

Jeff Atwood on January 3, 2005 03:18 AM

Just a heads up :) new version 1.0.4 is out

Alex on February 1, 2005 09:01 PM

This is now in Google's code repository.

http://code.google.com/p/syntaxhighlighter/

Mark Bernard on May 5, 2008 08:04 AM







(hear it spoken)


(no HTML)




Content (c) 2008 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.