This page is a demo/test showing all languages supported by highlight.js. Most of the code doesn't work :-).

You can see this page in several different styles bundled with the library or write your own (and contribute it back!)

## Automatically detected languages

Python |
    @requires_authorization
    def somefunc(param1, param2):
      r'''A docstring'''
      if param1 > param2: # interesting
        print 'Gre\'ater'
        print ''
      return (param2 - param1 + 1) or None

    class SomeClass:
        pass
Python's profiler output |
           261917242 function calls in 686.251 CPU seconds

           ncalls  tottime  filename:lineno(function)
           152824  513.894  {method 'sort' of 'list' objects}
        129590630   83.894  rrule.py:842(__cmp__)
        129590630   82.439  {cmp}
           153900    1.296  rrule.py:399(_iter)
    304393/151570    0.963  rrule.py:102(_iter_cached)
Ruby |
    class A < B; def self.create(object = User) object end end
    class Zebra; def inspect; "X#{2 + self.object_id}" end end

    module ABC::DEF
      include Comparable

      # @param test
      # @return [String] nothing
      def foo(test)
        Thread.new do |blockvar|
          ABC::DEF.reverse(:a_symbol, :'a symbol' + 'test' + test)
        end.join
      end

      def [](index) self[index] end
      def ==(other) other == self end
    end

    anIdentifier = an_identifier
    Constant = 1
Perl |
    # loads object
    sub load
    {
      my $flds = $c->db_load($id,@_) || do {
        Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
      };
      my $o = $c->_perl_new();
      $id12 = $id;
      $o->{'ID'} = $id12 + 123;
      $o->{'PAPA'} = $flds->{'PAPA'};
      #$o->{'SHCUT'} = $flds->{'SHCUT'};
      my $p = $o->props;
      my $vt;
      $string =~ m/^sought_text$/;
      for my $key (keys %$p)
      {
        if(${$vt.'::property'}) {
          $o->{$key . '_real'} = $flds->{$key};
          tie $o->{$key}, 'CMSBuilder::Property', $o, $key;
        } else {
          $o->{$key} = $flds->{$key};
        }
      }
      $o->save if delete $o->{'_save_after_load'};
      return $o;
    }
PHP |
    require_once 'Zend.php';
    require_once 'Zend/Uri/Exception.php';
    require_once 'Zend/Uri/Http.php';
    require_once 'Zend/Uri/Mailto.php';

    abstract class Zend_Uri
    {

      /**
       * Return a string representation of this URI.
       *
       * @see     getUri()
       * @return  string
       */
      public function __toString()
      {
          return $this->getUri();
      }

      static public function factory($uri = 'http')
      {
          $uri = explode(':', $uri, 2);
          $scheme = strtolower($uri[0]);
          $schemeSpecific = isset($uri[1]) ? $uri[1] : '';

          // Security check: $scheme is used to load a class file,
          // so only alphanumerics are allowed.
          if (!ctype_alnum($scheme)) {
              throw new Zend_Uri_Exception('Illegal scheme');
          }
      }
    }
Scala |
    object abstractTypes extends Application {
      abstract class SeqBuffer {
        type T; val element: Seq[T]; def length = element.length
      }
    }

    /** Turn command line arguments to uppercase */
    object Main {
      def main(args: Array[String]) {
        val res = for (a <- args) yield a.toUpperCase
        println("Arguments: " + res.toString)
      }
    }

    /** Maps are easy to use in Scala. */
    object Maps {
      val colors = Map("red" -> 0xFF0000,
                       "turquoise" -> 0x00FFFF,
                       "black" -> 0x000000,
                       "orange" -> 0xFF8040,
                       "brown" -> 0x804000)
      def main(args: Array[String]) {
        for (name <- args) println(
          colors.get(name) match {
            case Some(code) =>
              name + " has code: " + code
            case None =>
              "Unknown color: " + name
          }
        )
      }
    }
XML |
    <?xml version="1.0"?>
    <response value="ok" xml:lang="en">
      <text>Ok</text>
      <comment html_allowed="true"/>
      <ns1:description><![CDATA[
      CDATA is <not> magical.
      ]]></ns1:description>
      <a></a> <a/>
    </response>
HTML (with inline css and javascript) |
    <head>
      <title>Title</title>

      <style>
        body {
          width: 500px;
        }
      </style>

      <script>
        function someFunction() {
          return true;
        }
      </script>

    <body>
      <p class="something" id='12'>Something</p>
      <p class=something>Something</p>
      <!-- comment -->
      <p class>Something</p>
      <p class="something" title="p">Something</p>
    </body>
Django templates |
    {% if articles|length %}
    {% for article in articles %}

    {# Striped table #}
    <tr class="{% cycle odd,even %}">
      <td>{{ article|default:"Hi... "|escape }}</td>
      <td>{{ article.date|date:"d.m.Y" }}</td>
    </tr>

    {% endfor %}
    {% endif %}

    {% comment %}
    Comments may be long and
    multiline.
    {% endcomment %}
CSS |
    body,
    html {
      font: Tahoma, Arial, san-serif;
      background: url('hatch.png');
    }

    @import url('print.css');

    @media screen and (-webkit-min-device-pixel-ratio: 0) {
      @page :left {
        body:first-of-type pre::after {
          content: 'highlight: ' attr(class);
        }
    }

    #content {
      width: 100%; /* wide enough */
      height: 100%
    }

    p[lang=ru] {
      color: #F0F0F0; background: white;
    }
Javascript |
    function $initHighlight(block) {
      if (block.className.search(/\bno\-highlight\b/) != -1)
        return false;
      try {
        blockText(block);
      } catch (e) {
        if (e == 'Complex markup')
          return;
      }//try
      var classes = block.className.split(/\s+/);
      for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp start
        if (LANGUAGES[classes[i]]) {
          highlightLanguage(block, classes[i]);
          return;
        }//if
      }//for
      highlightAuto(block);
    }//initHighlight
VBScript |
    ' creating configuration storage and initializing with default values
    Set cfg = CreateObject("Scripting.Dictionary")

    ' reading ini file
    for i = 0 to ubound(ini_strings)
        s = trim(ini_strings(i))

        ' skipping empty strings and comments
        if mid(s, 1, 1) <> "#" and len(s) > 0 then
          ' obtaining key and value
          parts = split(s, "=", -1, 1)

          if ubound(parts)+1 = 2 then
            parts(0) = trim(parts(0))
            parts(1) = trim(parts(1))

            ' reading configuration and filenames
            select case lcase(parts(0))
              case "uncompressed""_postfix" cfg.item("uncompressed""_postfix") = parts(1)
              case "f"
                        options = split(parts(1), "|", -1, 1)
                        if ubound(options)+1 = 2 then
                          ' 0: filename,  1: options
                          ff.add trim(options(0)), trim(options(1))
                        end if
            end select
          end if
        end if
    next
Lua |
    --[[
    Simple signal/slot implementation
    ]]
    local signal_mt = {
        __index = {
            register = table.insert
        }
    }
    function signal_mt.__index:emit(... --[[ Comment in params ]])
        for _, slot in ipairs(self) do
            slot(self, ...)
        end
    end
    local function create_signal()
        return setmetatable({}, signal_mt)
    end

    -- Signal test
    local signal = create_signal()
    signal:register(function (signal, ...)
        print(...)
    end)
    signal:emit('Answer to Life, the Universe, and Everything:', 42)

    --[==[ [=[ [[
    Nested ]]
    multi-line ]=]
    comment ]==]
    [==[ Nested
    [=[ multi-line
    [[ string
    ]] ]=] ]==]
Delphi |
    TList=Class(TObject)
    Private
      Some: String;
    Public
      Procedure Inside;
    End;{TList}

    Procedure CopyFile(InFileName,var OutFileName:String);
    Const
      BufSize=4096; (* Huh? *)
    Var
      InFile,OutFile:TStream;
      Buffer:Array[1..BufSize] Of Byte;
      ReadBufSize:Integer;
    Begin
      InFile:=Nil;
      OutFile:=Nil;
      Try
        InFile:=TFileStream.Create(InFileName,fmOpenRead);
        OutFile:=TFileStream.Create(OutFileName,fmCreate);
        Repeat
          ReadBufSize:=InFile.Read(Buffer,BufSize);
          OutFile.Write(Buffer,ReadBufSize);
        Until ReadBufSize<>BufSize;
        Log('File '''+InFileName+''' copied'#13#10);
      Finally
        InFile.Free;
        OutFile.Free;
      End;{Try}
    End;{CopyFile}
Java |
    package l2f.gameserver.model;

    import java.util.ArrayList;

    /**
     * Mother class of all character objects of the world (PC, NPC...)<BR><BR>
     *
     */
    public abstract class L2Character extends L2Object
    {
      protected static final Logger _log = Logger.getLogger(L2Character.class.getName());

      public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0001; // not sure
      public static final Short ABNORMAL_EFFECT_POISON = 0x0002;

      public void detachAI() {
        _ai = null;
        //jbf = null;
        if (1 > 5) {
          return;
        }
      }

      public void moveTo(int x, int y, int z) {
        moveTo(x, y, z, 0);
      }

      /** Task of AI notification */
      @SuppressWarnings( { "nls", "unqualified-field-access", "boxing" })
      public class NotifyAITask implements Runnable {
        private final CtrlEvent _evt;

        public void run() {
          try {
            getAI().notifyEvent(_evt, null, null);
          } catch (Throwable t) {
            _log.warning("Exception " + t);
            t.printStackTrace();
          }
        }
      }

    }
C++ |
    #include <iostream>

    int main(int argc, char *argv[]) {

      /* An annoying "Hello World" example */
      for (unsigned i = 0; i < 0xFFFF; i++)
        cout << "Hello, World!" << endl;

      char c = '\n'; // just a test
      map <string, vector<string> > m;
      m["key"] = "\\\\"; // yeah, I know it's an error
    }
C# |
    using System;

    public class Program
    {
        /// <summary>The entry point to the program.</summary>
        /// <remarks>
        /// Using the Visual Studio style, the tags in this comment
        /// should be grey, but this text should be green.
        /// This comment should be green on the inside:
        /// <!-- I'm green! -->
        /// </remarks>
        public static int Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            string s = @"This
    ""string""
    spans
    multiple
    lines!";
            return 0;
        }
    }
RenderMan RSL |
    #define TEST_DEFINE 3.14
    /*	plastic surface shader
     *
     * 	Pixie is:
     * 	(c) Copyright 1999-2003 Okan Arikan. All rights reserved.
     */

    surface plastic (float Ka = 1, Kd = 0.5, Ks = 0.5, roughness = 0.1;
                     color specularcolor = 1;) {
      normal Nf = faceforward (normalize(N),I);
      Ci = Cs * (Ka*ambient() + Kd*diffuse(Nf)) + specularcolor * Ks *
           specular(Nf,-normalize(I),roughness);
      Oi = Os;
      Ci *= Oi;
    }
RenderMan RIB |
    FrameBegin 0
    Display "Scene" "framebuffer" "rgb"
    Option "searchpath" "shader" "+&:/home/kew"
    Option "trace" "int maxdepth" [4]
    Attribute "visibility" "trace" [1]
    Attribute "irradiance" "maxerror" [0.1]
    Attribute "visibility" "transmission" "opaque"
    Format 640 480 1.0
    ShadingRate 2
    PixelFilter "catmull-rom" 1 1
    PixelSamples 4 4
    Projection "perspective" "fov" 49.5502811377
    Scale 1 1 -1

    WorldBegin

    ReadArchive "Lamp.002_Light/instance.rib"
    Surface "plastic"
    ReadArchive "Cube.004_Mesh/instance.rib"
    # ReadArchive "Sphere.010_Mesh/instance.rib"
    # ReadArchive "Sphere.009_Mesh/instance.rib"
    ReadArchive "Sphere.006_Mesh/instance.rib"

    WorldEnd
    FrameEnd
MEL (Maya Embedded Language) |
    proc string[] getSelectedLights()

    {
      string $selectedLights[];

      string $select[] = `ls -sl -dag -leaf`;

      for ( $shape in $select )
      {
        // Determine if this is a light.
        //
        string $class[] = getClassification( `nodeType $shape` );

        if ( ( `size $class` ) > 0 && ( "light" == $class[0] ) )
        {
          $selectedLights[ `size $selectedLights` ] = $shape;
        }
      }

      // Result is an array of all lights included in

      // current selection list.
      return $selectedLights;
    }
SQL |
    BEGIN;
    CREATE TABLE "cicero_topic" (
        "id" serial NOT NULL PRIMARY KEY,
        "forum_id" integer NOT NULL,
        "subject" varchar(255) NOT NULL,
        "created" timestamp with time zone NOT NULL
    );
    ALTER TABLE "cicero_topic"
    ADD CONSTRAINT forum_id_refs_id_4be56999
    FOREIGN KEY ("forum_id")
    REFERENCES "cicero_forum" ("id")
    DEFERRABLE INITIALLY DEFERRED;

    -- Initials
    insert into "cicero_forum"
      ("slug", "name", "group", "ordering")
    values
      ('test', 'Forum for te''sting', 'Test', 0);

    -- Test
    select count(*) from cicero_forum;

    COMMIT;
SmallTalk |
    Object>>method: num
        "comment 123"
        | var1 var2 |
        (1 to: num) do: [:i | |var| ^i].
        Klass with: var1.
        Klass new.
        arr := #('123' 123.345 #hello Transcript var $@).
        arr := #().
        var2 = arr at: 3.
        ^ self abc

    heapExample
        "HeapTest new heapExample"
        "Multiline
        decription"
        | n rnd array time sorted |
        n := 5000.
        "# of elements to sort"
        rnd := Random new.
        array := (1 to: n)
                    collect: [:i | rnd next].
        "First, the heap version"
        time := Time
                    millisecondsToRun: [sorted := Heap withAll: array.
        1
            to: n
            do: [:i |
                sorted removeFirst.
                sorted add: rnd next]].
        Transcript cr; show: 'Time for Heap: ' , time printString , ' msecs'.
        "The quicksort version"
        time := Time
                    millisecondsToRun: [sorted := SortedCollection withAll: array.
        1
            to: n
            do: [:i |
                sorted removeFirst.
                sorted add: rnd next]].
        Transcript cr; show: 'Time for SortedCollection: ' , time printString , ' msecs'
Lisp |
    (defun prompt-for-cd ()
       "Prompts
        for CD"
       (prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6))
       (prompt-read "Artist" &rest)
       (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0)
      (if x (format t "yes") (format t "no" nil) ;and here comment
      )
      ;; second line comment
      '(+ 1 2)
      (defvar *lines*)                ; list of all lines
      (position-if-not #'sys::whitespacep line :start beg))
      (quote (privet 1 2 3))
      '(hello world)
      (* 5 7)
      (1 2 34 5)
      (:use "aaaa")
      (let ((x 10) (y 20))
        (print (+ x y))
      )
Ini file |
    ;Settings relating to the location and loading of the database
    [Database]
    ProfileDir=.
    ShowProfileMgr=smart
    Profile1_Name[] = "\|/_-=MegaDestoyer=-_\|/"
    DefaultProfile=True
    AutoCreate = no

    [AutoExec]
    Use="prompt"
    Glob=autoexec_*.ini
    AskAboutIgnoredPlugins=0
Apache |
    # rewrite`s rules for wordpress pretty url
    LoadModule rewrite_module  modules/mod_rewrite.so
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [NC,L]

    ExpiresActive On
    ExpiresByType application/x-javascript  "access plus 1 days"

    <Location /maps/>
      RewriteMap map txt:map.txt
      RewriteMap lower int:tolower
      RewriteCond %{REQUEST_URI} ^/([^/.]+)\.html$ [NC]
      RewriteCond ${map:${lower:%1}|NOT_FOUND} !NOT_FOUND
      RewriteRule .? /index.php?q=${map:${lower:%1}} [NC,L]
    </Location>
nginx |
    user  www www;
    worker_processes  2;
    pid /var/run/nginx.pid;
    error_log  /var/log/nginx.error_log  debug | info | notice | warn | error | crit;

    events {
        connections   2000;
        use kqueue | rtsig | epoll | /dev/poll | select | poll;
    }

    http {
        log_format main      '$remote_addr - $remote_user [$time_local] '
                             '"$request" $status $bytes_sent '
                             '"$http_referer" "$http_user_agent" '
                             '"$gzip_ratio"';

        send_timeout 3m;
        client_header_buffer_size 1k;

        gzip on;
        gzip_min_length 1100;

        #lingering_time 30;

        server {
            listen        one.example.com;
            server_name   one.example.com  www.one.example.com;
            access_log   /var/log/nginx.access_log  main;

            location / {
                proxy_pass         http://127.0.0.1/;
                proxy_redirect     off;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                charset            koi8-r;
            }

            location ~* \.(jpg|jpeg|gif)$ {
                root         /spool/www;
            }
        }
    }
Diff |
    Index: languages/ini.js
    ===================================================================
    --- languages/ini.js    (revision 199)
    +++ languages/ini.js    (revision 200)
    @@ -1,8 +1,7 @@
     hljs.LANGUAGES.ini =
     {
       case_insensitive: true,
    -  defaultMode:
    -  {
    +  defaultMode: {
         contains: ['comment', 'title', 'setting'],
         illegal: '[^\\s]'
       },

    *** /path/to/original timestamp
    --- /path/to/new      timestamp
    ***************
    *** 1,3 ****
    --- 1,9 ----
    + This is an important
    + notice! It should
    + therefore be located at
    + the beginning of this
    + document!

    ! compress the size of the
    ! changes.

      It is important to spell
DOS batch files |
    cd \
    copy a b
    ping 192.168.0.1
    @rem ping 192.168.0.1
    net stop sharedaccess
    del %tmp% /f /s /q
    del %temp% /f /s /q
    ipconfig /flushdns
    taskkill /F /IM JAVA.EXE /T

    cd Photoshop/Adobe Photoshop CS3/AMT/
    if exist application.sif (
        ren application.sif _application.sif
    ) else (
        ren _application.sif application.sif
    )

    taskkill /F /IM proquota.exe /T

    sfc /SCANNOW

    set path = test

    xcopy %1\*.* %2
Bash |
    #!/bin/bash

    ###### BEGIN CONFIG
    ACCEPTED_HOSTS="/root/.hag_accepted.conf"
    BE_VERBOSE=false
    ###### END CONFIG

    if [ "$UID" -ne 0 ]
    then
     echo "Superuser rights is required"
     exit 2
    fi

    genApacheConf(){
     if [[ "$2" = "www" ]]
     then
      full_domain=$1
     else
      full_domain=$2.$1
     fi
     host_root="${APACHE_HOME_DIR}$1/$2"
     echo -e "# Host $1/$2 :"
    }
Axapta |
    class ExchRateLoadBatch extends RunBaseBatch {
      ExchRateLoad rbc;
      container currencies;
      boolean actual;
      boolean overwrite;
      date beg;
      date end;

      #define.CurrentVersion(5)

      #localmacro.CurrentList
        currencies,
        actual,
        beg,
        end
      #endmacro
    }

    public boolean unpack(container packedClass) {
      container       base;
      boolean         ret;
      Integer         version    = runbase::getVersion(packedClass);

      switch (version) {
        case #CurrentVersion:
          [version, #CurrentList] = packedClass;
          return true;
        default:
          return false;
      }
      return ret;
    }
1С |
    #Если Клиент Тогда
    Перем СимвольныйКодКаталога = "ля-ля-ля"; //комментарий
    Функция Сообщить(Знач ТекстСообщения, ТекстСообщения2) Экспорт //комментарий к функции
      x=ТекстСообщения+ТекстСообщения2+"
      |строка1
      |строка2
      |строка3";
    КонецФункции
    #КонецЕсли

    // Процедура ПриНачалеРаботыСистемы
    //
    Процедура ПриНачалеРаботыСистемы()
      Обработки.Помощник.ПолучитьФорму("Форма").Открыть();
      d = '21.01.2008'
    КонецПроцедуры
AVR Assembler |
    ;* Title:       Block Copy Routines
    ;* Version:     1.1

    .include "8515def.inc"

        rjmp    RESET   ;reset handle

    .def    flashsize=r16       ;size of block to be copied

    flash2ram:
        lpm         ;get constant
        st  Y+,r0       ;store in SRAM and increment Y-pointer
        adiw    ZL,1        ;increment Z-pointer
        dec flashsize
        brne    flash2ram   ;if not end of table, loop more
        ret

    .def    ramtemp =r1     ;temporary storage register
    .def    ramsize =r16        ;size of block to be copied
Parser 3 |
    @CLASS
    base

    @USE
    module.p

    @BASE
    class

    # Comment for code
    @create[aParam1;aParam2][local1;local2]
      ^connect[mysql://host/database?ClientCharset=windows-1251]
      ^for[i](1;10){
        <p class="paragraph">^eval($i+10)</p>
        ^connect[mysql://host/database]{
          $tab[^table::sql{select * from `table` where a='1'}]
          $var_Name[some${value}]
        }
      }

      ^rem{
        Multiline comment with code: $var
        ^while(true){
          ^for[i](1;10){
            ^sleep[]
          }
        }
      }
      ^taint[^#0A]

    @GET_base[]
    ## Comment for code
      # Isn't comment
      $result[$.hash_item1[one] $.hash_item2[two]]
TeX |
    \documentclass{article}
    \usepackage[koi8-r]{inputenc}
    \hoffset=0pt
    \voffset=.3em
    \tolerance=400
    \newcommand{\eTiX}{\TeX}
    \begin{document}
    \section*{Highlight.js}
    \begin{table}[c|c]
    $\frac 12\, + \, \frac 1{x^3}\text{Hello \! world}$ & \textbf{Goodbye\~ world} \\\eTiX $ \pi=400 $
    \end{table}
    Ch\'erie, \c{c}a ne me pla\^\i t pas! % comment \b
    G\"otterd\"ammerung~45\%=34.
    $$
        \int\limits_{0}^{\pi}\frac{4}{x-7}=3
    $$
    \end{document}

## Special tests

Explicit Python highlighting |
    for x in [1, 2, 3]:
      count(x)
Language set on <pre> |
    for x in [1, 2, 3]:
      count(x)
HTML5-style language class (language-python) |
    for x in [1, 2, 3]:
      count(x)
Replacing TAB with 4 spaces |
    for x in [1, 2, 3]:
    	count(x)
Custom markup |
    <div id="contents">
      <p>Hello, World!
    </div>
Custom markup + TAB replacement |
    for x in [1, 2, 3]:
    	count(x)
    	if x == 3:
    		count(x + 1)
Disabled highlighting |
    <div id="contents">
      <p>Hello, World!
    </div>