Using dp.SyntaxHighlighter with Valid XHTML

Over at Rails Authority I use a great client-side syntax highlighter called SyntaxHighlighter to make code examples look nice, but it doesn’t support Valid XHTML , so I enhanced it to handle an XHTML-compatible style, e.g.:

<code class="code xml:nogutter">
    Your IP address is <%= @client_ip %>
  </code>

(Inspired by Ernest's post, linked above.)

To make this work, I made three changes to the shCore.js file (all within the HighlightAll function):

  1. In FindTagsByName, change line 618 that says:
    if(tags[i].getAttribute('name') == name)

    ... to:

    if(tags[i].getAttribute('name') == name || tags[i].className.indexOf(name)==0)
  2. Down a few lines at line 627, insert another FindByTags call for 'code':
    FindTagsByName(elements, name, 'code'); // Add this line
      FindTagsByName(elements, name, 'pre');
      FindTagsByName(elements, name, 'textarea');
  3. Further down, at line ~ 657 insert this right before options = options.split(':');:
    options = options.replace(new RegExp("^"+name+"\s"), ''); // Turn 'code ruby:option1:option2' into 'ruby:option1:option2'

This should be backward-compatible with the existing pre and textarea methods.

And here's the diff of the above steps:

$ diff shCore.js.orig shCore.js

618c618
<                       if(tags[i].getAttribute('name') == name)
---
>                       if(tags[i].getAttribute('name') == name || tags[i].className.indexOf(name)==0)
627a628
>       FindTagsByName(elements, name, 'code');
657a659
>               options = options.replace(new RegExp("^"+name+"\s"), ''); // Turn 'dp-hilite ruby:option1:option2' into 'ruby:option1:option2'