Color (syntax highlighting) within an HTML <code> tag

79.8k views Asked by At

In a code fragment like the following ...

    class Foo
    {
      internal Foo()
      {
        for (int i = 0; i < 42; ++i);
      }
    }

... its various keywords and so on are color-coded when they're displayed in my browsers.

When I do "View source", I don't see anything special in the HTML that would implement this color-coding.

How and/or where is this syntax-specific color-highlighting implemented, then? For example is it built-in to the browsers, or is it implemented by site-specific JavaScript editing the DOM within the browsers?

I find this a difficult question to Google for.

3

There are 3 answers

1
Asaph On BEST ANSWER

Stack Overflow uses Google's prettify JS library for doing syntax highlighting. It executes on the client side after the HTML has been delivered by the server. That's why you don't see it in the raw HTML source. If you have a browser plugin such as FireBug, you'll be able to inspect the DOM after prettify has done its magic.

Update 2020-09-14: Stack Overflow switched from Google's prettify to highlight.js.

3
David Brown On

Stack Overflow uses a Javascript library. There are quite a few out there, the most popular being SyntaxHighlighterDead link. My personal favorite is Chili, though.

3
Aaron Thoma On

There is an excellent FAQ What is syntax highlighting and how does it work? over on meta.SE.

It’s pretty extensive. For your convenience, i’ll quote the part most related to your question:


How does it work?

When creating or editing posts, syntax highlighting is assigned to the preview based on question's tags as soon as you stop typing for 5 seconds.

Stack Exchange does not have its own syntax highlighting engine. It uses highlight.js, and may not necessarily be using the latest release of that library. Therefore, any bugs and feature requests regarding syntax highlighting cannot be handled by Stack Exchange.

Why isn't my code being highlighted correctly?

[ Continue reading the original post … ]