Syntax Highlighting with Javascript
19th May 2003
If you were curious enough to dig around the source code of yesterday’s CSS tutorial, you may have noticed a couple of classes that didn’t appear to be doing anything:
<pre><code class="css">h1 {
color: navy;
border-bottom: 1px solid black;
}
</code></pre>
<pre><code class="html">...
<head>
<style type="text/css">
h1 {
color: blue;
}
...
</style>
...
</code></pre>
I added the classes in the hope that they would be useful some time in the future. This afternoon, the Internet connection in the University library stopped working so I decided to take the time to play with an idea I’ve been tossing around for a few weeks. The result: Javascript Syntax Highlighting. The concept is pretty simple—it grabs the code samples with css
or html
as the class, then uses regular expressions (along with some crafty callback functions) to add <span>
elements to specific bits of code to allow them to be highlighted. It works in Firebird / Mozilla but fails pitifully in IE 5, which appears not to support callbacks from the string.replace()
function. I haven’t tried it in IE 6 yet.
Unfortunately, it relies on the non-standards compliant innerHTML
property which causes it not to work in Mozilla in XML mode, so I can’t deploy it on my blog at the moment. Due to the way the regular expressions work I’m not entirely sure how I can rectify this using standard DOM methods, so I’m leaving it as it is for the moment.
More recent articles
- Weeknotes: more datasette-secrets, plus a mystery video project - 7th May 2024
- Weeknotes: Llama 3, AI for Data Journalism, llm-evals and datasette-secrets - 23rd April 2024
- Options for accessing Llama 3 from the terminal using LLM - 22nd April 2024
- AI for Data Journalism: demonstrating what we can do with this stuff right now - 17th April 2024
- Three major LLM releases in 24 hours (plus weeknotes) - 10th April 2024
- Building files-to-prompt entirely using Claude 3 Opus - 8th April 2024
- Running OCR against PDFs and images directly in your browser - 30th March 2024
- llm cmd undo last git commit - a new plugin for LLM - 26th March 2024
- Building and testing C extensions for SQLite with ChatGPT Code Interpreter - 23rd March 2024
- Claude and ChatGPT for ad-hoc sidequests - 22nd March 2024