Meta Stack Exchange is where users like you discuss bugs, features, and support issues that affect the software powering all 158 Stack Exchange communities.

What is meta?
Here's how it works:
  1. Any Stack Exchange user can ask a question
  2. The community provides support, votes on ideas, and reports bugs
  3. Your voice helps shape the way Stack Exchange operates

I was wondering how stackoverflow (wmd) solves syntax highlighting on source code snippets.

I understand that if text is marked as code it gets that <pre> CODE </pre> tags and that the wmd then recoginzes this as code snippet. But how is the syntax highlighting itself done?

I noticed that all this must happen based on javascript and no ajax and server based stuff is involved at all.

Can someone explain to me how this is done? How is the programming language of a code piece detected? Does this work like an 'exact' science (mean code is really detected as ie. Ruby code) or is is code highlighted done by a 'generic' code syntax highlighting?

share|improve this question
There are StackOverflow Weapons of Mass Destruction?! How do I get one? – Powerlord Sep 18 '09 at 13:25
It's <code><pre> CODE </pre></code> – Brad Gilbert Sep 18 '09 at 14:45
up vote 6 down vote accepted

SO, uses Google's prettify to do the syntax coloring. Prettify uses common language patterns to determine syntax coloring.

For further information see here.

The authoritative source on the languages that are understood by prettify are in prettify.js. Here an extract:

The lexer should work on a number of languages including C and friends,
Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk and a decent subset of Perl, but,
because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or CAML-like languages. If there's a language not mentioned here, then I don't know it, and don't know whether it works. If it has a C-like, Bash-like, or XML-like syntax then it should work passably.

share|improve this answer
So it is not exact science everytime but some kind generic, right? Do you know which languages are supported by prettify? – user136085 Sep 18 '09 at 9:54
I see. Thx for your answer! – user136085 Sep 18 '09 at 10:22

You must log in to answer this question.