prettify-2013.03.04/0000751000175000017500000000000012362771374012424 5ustar domidomiprettify-2013.03.04/examples/0000751000175000017500000000000012362767251014241 5ustar domidomiprettify-2013.03.04/examples/quine.html0000640000175000017500000000354412115200050016225 0ustar domidomi Making Quines Prettier

Making Quines Prettier

Below is the content of this page prettified. The <pre> element is prettified because it has class="prettyprint" and because the sourced script loads a JavaScript library that styles source code.

The line numbers to the left appear because the preceding comment <?prettify lang=html linenums=true?> turns on line-numbering and the stylesheet (see skin=sunburst in the <script src>) specifies that every fifth line should be numbered.





prettify-2013.03.04/CHANGES.html0000640000175000017500000001733012115200050014334 0ustar  domidomi
  
    
    Change Log
  
  
    README

    

Known Issues

Change Log

29 March 2007

4 Jul 2008

5 Jul 2008

14 Jul 2008

6 Jan 2009

21 May 2009

14 August 2009

3 October 2009

19 July 2010

7 September 2010

4 March 2011

29 March 2011

4 February 2013

24 February 2013

4 March 2013

prettify-2013.03.04/README.html0000640000175000017500000002645412115200050014230 0ustar domidomi Javascript code prettifier Languages : CH

Javascript code prettifier

Setup

  1. Download a distribution
  2. Include the script tag below in your document
    >script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js></script>
  3. See Getting Started to configure that URL with options you need.
  4. Look at the skin gallery and pick styles that suit you.

Usage

Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> and it will automatically be pretty printed.
The original Prettier
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded tags.
}
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded tags.
}

FAQ

For which languages does it work?

The comments in prettify.js are authoritative but the lexer should work on a number of languages including C and friends, Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, Makefiles, and Rust. It works passably on Ruby, PHP, VB, and Awk and a decent subset of Perl and Ruby, but, because of commenting conventions, but doesn't work on Smalltalk.

Other languages are supported via extensions:

Apollo Basic Clojure CSS Dart Erlang Go Haskell Lisp, Scheme Llvm Lua Matlab MLs:F#, Ocaml,SML Mumps Nemerle Pascal Protocol buffers R, S RD Scala SQL TCL Latek Visual Basic CHDL Wiki XQ YAML

If you'd like to add an extension for your favorite language, please look at src/lang-lisp.js and file an issue including your language extension, and a testcase.

How do I specify the language of my code?

You don't need to specify the language since prettyprint() will guess. You can specify a language by specifying the language extension along with the prettyprint class like so:

<pre class="prettyprint lang-html">
  The lang-* class specifies the language file extensions.
  File extensions supported by default include
    "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html",
    "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh",
    "xhtml", "xml", "xsl".
</pre>

You may also use the HTML 5 convention of embedding a code element inside the PRE and using language-java style classes. E.g.

<pre class="prettyprint"><code class="language-java">...</code></pre>

It doesn't work on <obfuscated code sample>?

Yes. Prettifying obfuscated code is like putting lipstick on a pig — i.e. outside the scope of this tool.

Which browsers does it work with?

It's been tested with IE 6, Firefox 1.5 & 2, and Safari 2.0.4. Look at the test page to see if it works in your browser.

What's changed?

See the change log

Why doesn't Prettyprinting of strings work on WordPress?

Apparently wordpress does "smart quoting" which changes close quotes. This causes end quotes to not match up with open quotes.

This breaks prettifying as well as copying and pasting of code samples. See WordPress's help center for info on how to stop smart quoting of code snippets.

How do I put line numbers in my code?

You can use the linenums class to turn on line numbering. If your code doesn't start at line number 1, you can add a colon and a line number to the end of that class as in linenums:52.

For example

<pre class="prettyprint linenums:4"
>// This is line 4.
foo();
bar();
baz();
boo();
far();
faz();
<pre>
produces
// This is line 4.
foo();
bar();
baz();
boo();
far();
faz();

How do I prevent a portion of markup from being marked as code?

You can use the nocode class to identify a span of markup that is not code.

<pre class=prettyprint>
int x = foo();  /* This is a comment  <span class="nocode">This is not code</span>
  Continuation of comment */
int y = bar();
</pre>
produces
int x = foo();  /* This is a comment  This is not code
  Continuation of comment */
int y = bar();

For a more complete example see the issue22 testcase.

I get an error message "a is not a function" or "opt_whenDone is not a function"

If you are calling prettyPrint via an event handler, wrap it in a function. Instead of doing

addEventListener('load', prettyPrint, false);
wrap it in a closure like
addEventListener('load', function (event) { prettyPrint() }, false);
so that the browser does not pass an event object to prettyPrint which will confuse it.

How can I customize the colors and styles of my code?

Prettify adds <span> with classes describing the kind of code. You can create CSS styles to matches these classes. See the theme gallery for examples.

I can't add classes to my code (because it comes from Markdown, etc.)

Instead of <pre class="prettyprint ..."> you can use a comment or processing instructions that survives processing instructions : <?prettify ...?> works as explained in Getting Started




prettify-2013.03.04/Makefile0000640000175000017500000000747012115200050014042 0ustar domidomiSHELL := /bin/bash CLOSURE_COMPILER=java -jar tools/closure-compiler/compiler.jar \ --warning_level VERBOSE \ --language_in ECMASCRIPT5 \ --compilation_level ADVANCED_OPTIMIZATIONS \ --charset US-ASCII # Don't specify --charset=UTF-8. If we do, then non-ascii codepoints # that do not correspond to line terminators are converted # to UTF-8 sequences instead of being emitted as ASCII. # This makes the resulting JavaScript less portable. YUI_COMPRESSOR=java -jar tools/yui-compressor/yuicompressor-2.4.4.jar \ --charset UTF-8 TAR_ROOT=distrib/google-code-prettify all: distrib clean: rm -rf distrib.tstamp distrib src/prettify.js src/run_prettify.js src/prettify.js: js-modules/*.js js-modules/*.pl @if [ -e "$@" ]; then chmod +w "$@"; fi @perl js-modules/js_include.pl "$$(basename $@)" > "$@" @if [ -e "$@" ]; then chmod -w "$@"; fi src/run_prettify.js: js-modules/*.js js-modules/*.pl @if [ -e "$@" ]; then chmod +w "$@"; fi @perl js-modules/js_include.pl "$$(basename $@)" > "$@" @if [ -e "$@" ]; then chmod -w "$@"; fi distrib: distrib.tstamp distrib/prettify-small.tgz distrib/prettify-small.zip distrib/prettify-small.tar.bz2 @wc -c distrib/prettify-small.{tar.bz2,tgz,zip} \ | grep -v total distrib.tstamp: src/prettify.js src/run_prettify.js src/*.js src/*.css @echo Compiling @mkdir -p $(TAR_ROOT) @for f in src/*.css; do \ $(YUI_COMPRESSOR) --type css $$f \ > $(TAR_ROOT)/$$(basename $$f); \ wc -c $$f $(TAR_ROOT)/$$(basename $$f) \ | grep -v total; \ done @$(CLOSURE_COMPILER) --js src/prettify.js \ --externs tools/closure-compiler/console-externs.js \ --externs tools/closure-compiler/amd-externs.js \ --define IN_GLOBAL_SCOPE=true \ --output_wrapper='!function(){%output%}()' \ > $(TAR_ROOT)/prettify.js @wc -c src/prettify.js $(TAR_ROOT)/prettify.js \ | grep -v total @$(CLOSURE_COMPILER) --js src/run_prettify.js \ --externs tools/closure-compiler/console-externs.js \ --externs tools/closure-compiler/amd-externs.js \ --define IN_GLOBAL_SCOPE=false \ --output_wrapper='!function(){%output%}()' \ > $(TAR_ROOT)/run_prettify.js @wc -c src/run_prettify.js $(TAR_ROOT)/run_prettify.js \ | grep -v total @for f in src/lang*.js; do \ if [ $$f -nt $(TAR_ROOT)/$$(basename $$f) ]; then \ $(CLOSURE_COMPILER) --js $$f --externs js-modules/externs.js \ | perl -pe 's/\bPR\.PR_ATTRIB_NAME\b/"atn"/g; \ s/\bPR\.PR_ATTRIB_VALUE\b/"atv"/g; \ s/\bPR\.PR_COMMENT\b/"com"/g; \ s/\bPR\.PR_DECLARATION\b/"dec"/g; \ s/\bPR\.PR_KEYWORD\b/"kwd"/g; \ s/\bPR\.PR_LITERAL\b/"lit"/g; \ s/\bPR\.PR_PLAIN\b/"pln"/g; \ s/\bPR\.PR_PUNCTUATION\b/"pun"/g; \ s/\bPR\.PR_STRING\b/"str"/g; \ s/\bPR\.PR_TAG\b/"tag"/g; \ s/\bPR\.PR_TYPE\b/"typ"/g;' \ > $(TAR_ROOT)/$$(basename $$f); \ wc -c $$f $(TAR_ROOT)/$$(basename $$f) \ | grep -v total; \ fi \ done @touch distrib.tstamp lang-aliases : lang-aliases.tstamp lang-aliases.tstamp : distrib.tstamp @tools/lang-handler-aliases.sh \ distrib/sources/google-code-prettify/src \ | perl -ne 'system("cp $$1 $$2") if m/^(\S+) (\S+)$$/ && ! -e $$2' \ && touch lang-aliases.tstamp %.tgz: %.tar @gzip -c -9 $^ > $@ %.tar.bz2: %.tar @bzip2 -k -9f $^ distrib/prettify-small.tar: distrib.tstamp tar cf $@ -C distrib google-code-prettify distrib/prettify-small.zip: distrib.tstamp @pushd distrib >& /dev/null; \ rm -f ../$@; \ zip -q -9 -r ../$@ google-code-prettify; \ popd >& /dev/null distrib/prettify.tar: distrib.tstamp mkdir -p distrib/sources/google-code-prettify cp -fr CHANGES.html COPYING README.html Makefile \ examples js-modules src styles tests tools \ distrib/sources/google-code-prettify tar cf distrib/prettify.tar -C distrib/sources google-code-prettify prettify-2013.03.04/tests/0000751000175000017500000000000012362767251013565 5ustar domidomiprettify-2013.03.04/tests/large_input_test.html0000640000175000017500000000676012115200050020003 0ustar domidomi Tests of Prettifier w/ large data files
prettify-2013.03.04/tests/prettify_test_2.html0000640000175000017500000025661612115200050017570 0ustar domidomi Code Prettifier

XQuery mode

From http://www.patrick-wied.at/static/xquery/prettify/
(: 
	Took some of Mike Brevoort's xquery code samples because they are nice and show common xquery syntax 
:)
 
  (:~
   : Given a sequence of version URIs, publish all of these versions of each document
   : If there is a version of the same document already published, unpublish it 1st
   :
   : When "publish" is referred to, we mean that it is put into the PUBLISHED collection
   : unpublish removes content from this collection
   : @param $version_uris - sequence of uris of versions of managed documents to publish
   :)
  declare function comoms-dls:publish($version_uris as item()*) {
      for $uri in $version_uris
      let $doc := fn:doc($uri)
      let $managed_base_uri := $doc/node()/property::dls:version/dls:document-uri/text()
      let $existing :=  comoms-dls:publishedDoc($managed_base_uri)
      let $unpublishExisting := if($existing) then comoms-dls:unpublishVersion((xdmp:node-uri($existing)))  else ()
      let $addPermissions := dls:document-add-permissions($uri, (xdmp:permission('mkp-anon', 'read')))
      return
          dls:document-add-collections($uri, ("PUBLISHED"))    
  };
 
  declare function comoms-dls:publishLatest($uri) {
      (: TODO check if it's in the draft collection probably :)
 
      let $latest_version_uri := comoms-dls:latestVersionUri($uri)
      let $log:= xdmp:log(fn:concat("latest: ", $latest_version_uri))    
      let $log:= xdmp:log(fn:concat("uri: ", $uri))            
      return comoms-dls:publish($latest_version_uri)    
 
  };
 
  declare function comoms-dls:latestVersionUri($uri) {
      let $latest_version_num :=
          (
          for $version in dls:document-history($uri)/dls:version
          order by fn:number($version//dls:version-id/text()) descending
          return $version//dls:version-id/text()
          )[1]
 
 
      return dls:document-version-uri($uri, $latest_version_num)
  };
 
  declare function comoms-dls:unpublish($uris as item()*) {
      for $uri in $uris
      return
          let $published_doc := comoms-dls:publishedDoc($uri)
          return
              if($published_doc) then
                  let $published_version_uri := xdmp:node-uri($published_doc)
                  return comoms-dls:unpublishVersion($published_version_uri)        
              else
                  ()
  };
 
  declare function comoms-dls:latestPublishedDocAuthor($uri) {
      let $author_id := doc($uri)/property::dls:version/dls:author/text()
      return
          if($author_id) then
              comoms-user:getUsername($author_id)
          else
              ()
 
  };
 
  (:~
   : Given a sequence of version URIs, unpublish all of these versions of each document
   :)
  declare function comoms-dls:unpublishVersion($version_uris as item()*) {
      for $uri in $version_uris
      return
          let $removePermissions := dls:document-remove-permissions($uri, (xdmp:permission('mkp-anon', 'read')))
          return dls:document-remove-collections($uri, ("PUBLISHED"))        
  };
 
  (:~
   : Given the base URI of a managed piece of content, return the document of the node
   : of the version that is published
   :)
  declare function comoms-dls:publishedDoc($uri) {
      fn:collection("PUBLISHED")[property::dls:version/dls:document-uri = $uri]
  };
 
 
  (:~
   : Test if any version of the managed document is published
   :)
  declare function comoms-dls:isPublished($uri) {
      if( comoms-dls:publishedDoc($uri)) then
          fn:true()
      else
          fn:false()
  };
 
 
  declare function comoms-dls:publishedState($uri) {
      let $doc := comoms-dls:publishedDoc($uri)
      let $published_uri := if($doc) then xdmp:node-uri($doc) else ()
      let $latest := comoms-dls:latestVersionUri($uri)
      return
          if($doc) then
              if($latest ne $published_uri) then
                  "stale"
              else
                  "published"
          else
              "unpublished"
  };
 
 
  declare function comoms-dls:getManagedDocUri($uri) {
      let $doc := fn:doc($uri)
      let $managed_uri := $doc/property::dls:version/dls:document-uri/text()
      let $managed_uri := if($managed_uri) then $managed_uri else $uri
      return $managed_uri
  };
 
  (:~
   : Given a manage content url (e.g. /content/123456.xml) return the appropriate
   : version of the document based on what stage collection is being viewed and
   : what's published
   :
   : @param $uri a manage content url (e.g. /content/123456.xml) - NOT A VERSIONED URI
   :)
  declare function comoms-dls:doc($uri) {
      let $doc := fn:root(comoms-dls:collection()[property::dls:version/dls:document-uri = $uri][1])
      return
          if($doc) then
              $doc
          else
              let $managedDocInCollection := comoms-dls:collection-name() = xdmp:document-get-collections($uri)
              return
                  if($managedDocInCollection) then
                      fn:doc($uri)
                  else
                      ()
  };
 
  (:~
   : Get the collection to be used when querying for content
   : THIS or comoms-dls:collection-name() SHOULD BE USED WHEN BUILDING ANY QUERY FOR MANAGED CONTENT
   :)
  declare function comoms-dls:collection()  {
      fn:collection( comoms-dls:collection-name() )
  };
 
  (:~
   : Get the collection nameto be used when querying for content
   : THIS or comoms-dls:collection() SHOULD BE USED WHEN BUILDING ANY QUERY FOR MANAGED CONTENT
   :)
  declare function comoms-dls:collection-name() as xs:string {
      let $default_collection := "PUBLISHED"
      return
          if(comoms-user:isAdmin()) then
              let $pub_stage_collection_cookie := comoms-util:getCookie("COMOMS_COLLECTION")
              return
                  if($pub_stage_collection_cookie) then
                      $pub_stage_collection_cookie
                  else
                      $default_collection
          else
              $default_collection
  };
 
  (:~
   : Check if the published collection is being viewed
   :)
  declare function comoms-dls:isViewingPublished() {
      if(comoms-dls:collection-name() = "PUBLISHED") then
          fn:true()
      else
          fn:false()
  };
 
  (:~
   : Get the best URL for the content URI.
   : This is either the default URI based on detail type or should also take
   : into account friendly urls and navigation structures to figure out the
   : best choice
   :)
  declare function comoms-dls:contentUrl($uri) {
 
      (: TODO: add friendly URL and nav structure logic 1st :)
 
      let $doc := fn:doc($uri)
      let $managedDocUri := $doc/property::dls:version/dls:document-uri
      let $uri := if($managedDocUri) then $managedDocUri else $uri
      let $type := $doc/node()/fn:name()
      let $content_id := fn:tokenize( fn:tokenize($uri, "/")[3], "\.")[1]
      return
          fn:concat("/", $type, "/", $content_id)
  };
 
  (:
   :
   :  gets list of doc versions and uri.
   :
   :)
  declare function comoms-dls:versionHistory($uri) {
      let $published_doc := comoms-dls:publishedDoc($uri)
      let $published_uri := if($published_doc) then xdmp:node-uri($published_doc) else ()
      return
      <versions>
          {
          for $version in dls:document-history($uri)/dls:version
            let $version_num := $version/dls:version-id/text()
            let $created := $version/dls:created/text()
            let $author_id := $version/dls:author/text()
            let $author := comoms-user:getUsername($author_id)
 
 
            let $note := $version/dls:annotation/text()
            let $version_uri := xdmp:node-uri(dls:document-version($uri, $version_num))
            let $published := $published_uri eq $version_uri
            return
              <version>
                  <version-number>{$version_num}</version-number>
                  <created>{$created}</created>                
                  <author>{$author}</author>
                  <published>{$published}</published>
                  <version-uri>{$version_uri}</version-uri>
              </version>  
          }        
      </versions>
  };
 
 
 
 
 
 
  (: ########################################################################### :)
  (: PRIVATE FUNCTIONS :)
  (: ########################################################################### :)
 
  declare function comoms-dls:_import() {
      "xquery version '1.0-ml';
       import module namespace dls = 'http://marklogic.com/xdmp/dls' at '/MarkLogic/dls.xqy'; "
  };  
 
(: ----
---- :)
xquery version '1.0-ml';
declare variable $URI as xs:string external;
 
declare function local:document-move-forest($uri as xs:string, $forest-ids as xs:unsignedLong*)
{
  xdmp:document-insert(
    $uri,
    fn:doc($uri),
    xdmp:document-get-permissions($uri),
    xdmp:document-get-collections($uri),
    xdmp:document-get-quality($uri),
    $forest-ids
  )
};
 
let $xml :=
  <xml att="blah" att2="blah">
    sdasd<b>asdasd</b>
  </xml>
(: -------- :)
for $d in fn:doc("depts.xml")/depts/deptno
let $e := fn:doc("emps.xml")/emps/emp[deptno = $d]
where fn:count($e) >= 10
order by fn:avg($e/salary) descending
return
   <big-dept>
      {
      $d,
      <headcount>{fn:count($e)}</headcount>,
      <avgsal>{fn:avg($e/salary)}</avgsal>
      }
   </big-dept>
(: -------- :)
declare function local:depth($e as node()) as xs:integer
{
   (: A node with no children has depth 1 :)
   (: Otherwise, add 1 to max depth of children :)
   if (fn:empty($e/*)) then 1
   else fn:max(for $c in $e/* return local:depth($c)) + 1
};
 
local:depth(fn:doc("partlist.xml"))
 
(: -------- :)
<html><head/><body>
{
  for $act in doc("hamlet.xml")//ACT
  let $speakers := distinct-values($act//SPEAKER)
  return
    <div>{ string($act/TITLE) }</h1>
      <ul>
      {
        for $speaker in $speakers
        return <li>{ $speaker }</li>
      }
      </ul>
    </div>
}
</body></html>
(: -------- :)
{
	for $book in doc("books.xml")//book
        return
	if (contains($book/author/text(),"Herbert") or contains($book/author/text(),"Asimov"))
		then $book
	else $book/text()
	
	let $let := <x>"test"</x>
	return element element {
	attribute attribute { 1 },
	element test { 'a' },
	attribute foo { "bar" },
	fn:doc()[ foo/@bar eq $let ],
	//x }
}
(: -------- :)
<bib>
 {
  for $b in doc("http://bstore1.example.com/bib.xml")/bib/book
  where $b/publisher = "Addison-Wesley" and $b/@year > 1991
  return
    <book year="{ $b/@year }">
     { $b/title }
    </book>
 }
</bib>
(: -------- :)

Nemerle code

class Set ['a]
{
  mutable storage : list ['a] = [];
  public Add (e : 'a) : void
  {
    when (! Contains (e))
      storage ::= e;
  }
  public Contains (e : 'a) : bool
  {
    storage.Contains (e)
  }
}
 
def s1 = Set ();
s1.Add (3);
s1.Add (42);
assert (s1.Contains (3));
// s1.Add ("foo"); // error here!
def s2 = Set ();
s2.Add ("foo");
assert (s2.Contains ("foo"));

Tex support

% resume.tex
% vim:set ft=tex spell:
\documentclass[10pt,letterpaper]{article}
\usepackage[letterpaper,margin=0.8in]{geometry}
\usepackage{mdwlist}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\pagestyle{empty}
\setlength{\tabcolsep}{0em}

Issue 144

Escaped quotes in bash.
#! /bin/bash
# toascii.sh
for i in $(echo $* | fold -w 1);do
  printf "%x " \'$i;
done;
echo

Issue 145

<script type="text/javascript">
<!--
        var target = $$.css('backgroundImage').replace(/^url[\(\)'"]/g, '');

        // nice long chain: wrap img element in span
        $$.wrap('<span style="position: relative;"></span>')
-->
</script>

Clojure Syntax Highlighting

; Clojure test comment
(ns test
 (:gen-class))

(def foo "bar")
(defn bar [arg1 arg2 & args]
  "sample function"
  (for [arg args]
    (prn arg)))

(bar "foo" "bar" "blah" :baz)

HTML 5 language on code

The text is specified to be lisp by the class attribute. Semicolon is normally a valid punctuation character but in lisp it is a comment so should be colored as a comment if the className is being properly parsed.

; foo

HTML 5 language on nested code element

The language is attached to a CODE element inside a PRE.

; foo

HTML 5 language on nested code element not foiled by space

The language is attached to a CODE element inside a PRE and there is space between the PRE element's tags and CODE element's tags.


; foo

HTML 5 nested code element language ignored if not only content

The below is not treated as lisp despite there being a lisp language specifier on the contained CODE element, the CODE element does not wrap all non-space content.

before CODE
; foo

The language is attached to an HTML5 comment that looks like an XML processing instruction.

; foo

The language is attached to a regular HTML5 comment that looks like an XML processing instruction.

; foo

The language is attached to a regular HTML5 comment that looks like an XML processing instruction.

; foo

The language is attached to a regular HTML5 comment that looks like an XML processing instruction.

; foo

Issues 185 and 261: Don't reprettify prettified content

"No tag backs."
  1. "No tag backs."

Issue 201: C type not full word

static Persistent<String> listeners_symbol;

Pascal w/ language specified

(* some comment here *)
PROCEDURE TestCase.AssertEquals(msg:String; expect, act:Longint);
VAR ex, ac:String;
BEGIN
  IF expect <> act THEN
  BEGIN
    Str(expect, ex);
    Fail(Concat(msg,' expected ',ex,' but was ',ac));
  END;

  factors := new(ArrayListPtr, Init);

  FOR candidate := 2 TO i DO
  BEGIN
    WHILE i MOD candidate = 0 DO
    BEGIN
      factors^.Add(candidate);
      i := i DIV candidate;
    END;
  END;
END;

BASIC w/ language specified

200 REM ----- method teardown
210 PRINT "green"
220 RETURN
470 IF af=0 THEN GOTO 520
480 FOR j=1 TO af
500 ac=pf(j) : me$=STR$(j)+". factor" : GOSUB 100
510 NEXT
530 RETURN
1000 DATA "one", 1, 0

Dart language handler

part of myLib;

part 'something.dart';

import 'dart:math' as test show foo, bar;

class Point {
  final num x, y;

  Point(this.x, this.y);
  Point.zero() : x = 0, y = 0;  // Named constructor
                                // with an initializer list.

  num distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);
  }
}

// This is a single-line comment.

/*
This is a
multiline comment.
*/

main() {
  Point p = new Point(7, 12);
  String thing = 'It\'s awesome!';
  String thing2 = '''
This is a test! \'''
This is the end of the test''';
  String thing3 = r"""
This is a raw
multiline string!""";
  num x = 0x123ABC;
  num y = 1.8e-12;
  bool flag = false;
  String raw = r"This is a raw string, where \n doesn't matter";
}

TCL_lang

#!/bin/tclsh
proc fib {n} {
    set a 0
    set b 1
    while {$n > 0} {
        set tmp $a
        set a [expr $a + $b]
        set b $tmp
        incr n -1
    }
    return $a
}

R, S language support

### Example R script for syntax highlighting

# This is a comment

## Valid names
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV0123456789._a <- NULL
.foo_ <- NULL
._foo <- NULL

## Invalid names
0abc <- NULL
.0abc <- NULL
abc+cde <- NULL

## Reserved Words
NA
NA_integer_
NA_real_
NA_character_
NA_complex_
NULL
NaN
Inf
## Not reserved
NULLa <- NULL
NULL1 <- NULL
NULL. <- NULL
NA_foo_ <- NULL

## Numbers
12345678901
123456.78901
123e3
123E3
1.23e-3
1.23e3
1.23e-3
## integer constants
123L
1.23L
## imaginary numbers
123i
-123i
123e4i
123e-4i
## Hex numbers
0xabcdefABCDEF01234
0xabcp123
0xabcP123
## Not hex
0xg

## Special operators %xyz%
## %xyz%
1 %% 2
diag(2) %*% diag(2)
1 %/% 2
1 %in% 1:10
diag(2) %o% diag(2)
diag(2) %x% diag(2)
`%foo bar%` <- function(x, y) x + y
1 %foo bar% 2

## Control Structures (3.2) and Function
## if, else
if (TRUE) print("foo") else print("bar")
## For, in
for(i in 1:5) {
    print(i)
}
## While, break
i <- 1
while (TRUE) {
    i <- i + 1
    if (i > 3) break
}
## Repeat
repeat {1+1}
## Switch
x <- 3
switch(x, 2+2, mean(1:10), rnorm(5))
## Function, dot-dot-dot, return
foo <- function(...) {
    return(sum(...))
}
# Not keywords
functiona <- 2 + 2
function. <- 2 + 2
function1 <- 2 + 2


## Grouping Tokens 10.3.7
## Parentheses
1 + (2 + 3)
## brackets
foo <- function(a) {
    a + 1
}

## Indexing 10.3.8
## []
bar <- 1:10
bar[3]
## [[]]
foo <- list(a=1, b=2, c=3)
foo[["a"]]
## $
foo$a
foo$"a"

## Operators
2 - 2
2 + 2
2 ~ 2
! TRUE
?"help"
1:2
2 * 2
2 / 2
2^2
2 < 2
2 > 2
2 == 2
2 >= 2
2 <= 2
2 != 2
TRUE & FALSE
TRUE && FALSE
TRUE | FALSE
TRUE || FALSE
foo <- 2 + 2
foo = 2 + 2
2 + 2 -> foo
foo <<- 2 + 2
2 + 2 ->> foo
base:::sum
base::sum

## Strings
foo <- "hello, world!"
foo <- 'hello, world!'
foo <- "Hello, 'world!"
foo <- 'Hello, "world!'
foo <- 'Hello, \'world!\''
foo <- "Hello, \"world!\""
foo <- "Hello,
world!"
foo <- 'Hello,
world!'

## Backtick strings
`foo123 +!"bar'baz` <- 2 + 2

MUMPS

HDR ; -- prt/display header
 N X,I
 I '$D(VALMHDR) X:$G(VALM("HDR"))]"" VALM("HDR")
 ; -- prt hdr line
 W:'$D(VALMPG1) @IOF K VALMPG1
 W:VALMCC $C(13)_IOUON_$C(13)_IOINHI_$C(13)       ; -- turn on undln/hi
 I $E(IOST,1,2)="C-" D IOXY^VALM4(0,0)            ; -- position cursor
 W $E(VALM("TITLE"),1,30)                         ; -- prt title
 W:VALMCC IOINORM,IOUON                           ; -- turn off hi
 W $J("",30-$L(VALM("TITLE")))                    ; -- fill in w/blanks
 I $E(IOST,1,2)="C-" W $C(13) D IOXY^VALM4(30,0)  ; -- position cursor
 W $J("",((VALMWD-80)/2)),$$HTE^XLFDT($H,1),$J("",10+((VALMWD-80)/2)),"Page: ",$J(VALMPGE,4)," of ",$J($$PAGE^VALM4(VALMCNT,VALM("LINES")),4)_$S($D(VALMORE):"+",1:" ") ; -- prt rest of hdr
 W:VALMCC IOUOFF I $E(IOST,1,2)="C-" D IOXY^VALM4(0,0) ; -- turn off undln
 F I=1:1:VALM("TM")-3 W !,$S('$D(VALMHDR(I)):"",$L(VALMHDR(I))>(VALMWD-1):$$EXTRACT^VALM4($G(VALMHDR(I))),1:VALMHDR(I)) ; -- prt hdr
 Q

LLVM

Hello world module
; Declare the string constant as a global constant.
@.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00"

; External declaration of the puts function
declare i32 @puts(i8* nocapture) nounwind

; Definition of main function
define i32 @main() {   ; i32()*
  ; Convert [13 x i8]* to i8  *...
  %cast210 = getelementptr [13 x i8]* @.str, i64 0, i64 0

  ; Call puts function to write out the string to stdout.
  call i32 @puts(i8* %cast210)
  ret i32 0
}

; Named metadata
!1 = metadata !{i32 42}
!foo = !{!1, null}

Issue 217 : Regex following '!'

if(!/^https?:\/\//i.test(val) && foo == 'bar') {
    val = 'http://' + val;
}

Issue 32 : Matlab

%%%%%%%%%%%%%%%%%% DATA TYPES %%%%%%%%%%%%%%%%%%

v = [1,2,3;4,5,6];
v(v>4) = 0;

s = struct('key',1, 'key2','string');
s.key = 2;

C = cell(1,2);
C{1,1} = 0:9;

double(1)
single(1)
uint8(1)
int8(1)

%%%%%%%%%%%%%%%%%% STRINGS & TRANSPOSE %%%%%%%%%%%%%%%%%%

plot(data');
legend(labels)

str = 'asdasd';     % this is a string
str = 'asdas';
str = 'sdasd''sdasd';

str = ['one' 'two' 'three'];
str = strcat('one', 'two', 'three');

% matrix transpose
M = rand(3,3)';
x = M.';
x = [10 20; 30, 40]';
disp(x')
fprintf('%d\n', x(:)')      % with comment
{1,2}'                      % another comment

%%%%%%%%%%%%%%%%%% LINE CONTINUATION %%%%%%%%%%%%%%%%%%

[1 20; ...
30 4]

['gdgsd'...
'sdfs']

{...
'sdasd' ;
'asdsad'}

%%%%%%%%%%%%%%%%%% SYSTEM COMMANDS %%%%%%%%%%%%%%%%%%

!touch file.txt

%%%%%%%%%%%%%%%%%% COMMAND OUTPUT %%%%%%%%%%%%%%%%%%

>> 1+1
ans =
     2

>> 1+1

ans =

     2

%%%%%%%%%%%%%%%%%% KEYWORDS %%%%%%%%%%%%%%%%%%

function ret = fcn(in)
	ret = sum(in.^2);
end

classdef CC < handle
	properties (SetAccess = public)
		x = 0;
	end
	methods
		function this = CC(varargin)
			this.x = 9;
		end
	end
end

x = [];
parfor i=1:10
	x[i] = i;
end

true ~= false

if x==1
	true
elseif
	false
else
	return
end

while true
	continue
	break
end

try
	error('aa:aa', 'asdasd')
catch ME
	warning(ME)
end

switch x
	case 1
		disp(1)
	otherwise
		0
end

%%%%%%%%%%%%%%%%%% NUM LITERALS %%%%%%%%%%%%%%%%%%

1
1.
.1
1.0
-1
-1.
-.1
-1.0
+10
+01.
+.1
+1.0
1e1
1e-1
1.e1
1.e-1
1.0e1
1.0e-1
.1e1
.1e-1
-.1e+1
+1.e-1

1i
.10j
-1.001i
+1e-100j
-.10e-01i

% unary vs binary operators
1+1
1+ 1
1 +1
1 + 1
+1+1
+1+ 1
+1 +1
+1 + 1

%%%%%%%%%%%%%%%%%% COMMENTS %%%%%%%%%%%%%%%%%%

% % comment % %
   % comment
% comment
%# comment
%% comment
%#x = sum(x);

%{
block comment
%}

%{
%}

%{

%}

%{
1
2
%}

%{
% sdf {}
sdf
%asda{}
sfds
%}

    %{
dsf
        %}

%{%}

%{ zzz=10; %}

%{%x=10;%}

%{  x
a=10;
%}

%{
%a=10;
%}   x

% nested block comments fail
%{
dfsdf
%{
xxx
%}
dfsdf
%}

% fails here!
%{
x=10;
%%{
%%}
y=20;
%}
prettify-2013.03.04/tests/prettify_test.html0000640000175000017500000034374312115200050017345 0ustar domidomi Code Prettifier

Bash

#!/bin/bash

# Fibonacci numbers
# Writes an infinite series to stdout, one entry per line
function fib() {
  local a=1
  local b=1
  while true ; do
    echo $a
    local tmp=$a
    a=$(( $a + $b ))
    b=$tmp
  done
}

# output the 10th element of the series and halt
fib | head -10 | tail -1

Bash w/ language specified

#!/bin/bash

# Fibonacci numbers
# Writes an infinite series to stdout, one entry per line
function fib() {
  local a=1
  local b=1
  while true ; do
    echo $a
    local tmp=$a
    a=$(( $a + $b ))
    b=$tmp
  done
}

# output the 10th element of the series and halt
fib | /usr/bin/*head -10 | tail -1

Issue 165

# Comment
local $x = ${#x[@]}  # Previous is not a comment
# A comment

C

#include <stdio.h>

/* the n-th fibonacci number.
 */
unsigned int fib(unsigned int n) {
  unsigned int a = 1, b = 1;
  unsigned int tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}

main() {
  printf("%u", fib(10));
}

C w/ language specified

#include <stdio.h>

/* the nth fibonacci number. */
uint32 fib(unsigned int n) {
  uint32 a = 1, b = 1;
  uint32 tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}

void main() {
  size_t size = sizeof(wchar_t);
  ASSERT_EQ(size, 1);
  printf("%u", fib(10));
}

#define ZERO 0 /* a
  multiline comment */

C++

#include <iostream>

using namespace std;

//! fibonacci numbers with gratuitous use of templates.
//! \param n an index into the fibonacci series
//! \param fib0 element 0 of the series
//! \return the nth element of the fibonacci series
template <class T>
T fib(unsigned int n, const T& fib0) {
  T a(fib0), b(fib0);
  for (; n; --n) {
    T tmp(a);
    a += b;
    b = tmp;
  }
  return a;
}

int main(int argc, char **argv) {
  cout << fib(10, 1U);
}

C++ w/ language specified

#include <iostream>

using namespace std;

//! fibonacci numbers with gratuitous use of templates.
//! \param n an index into the fibonacci series
//! \param fib0 element 0 of the series
//! \return the nth element of the fibonacci series
template <class T>
T fib(int n, const T& fib0) {
  T a(fib0), b(fib0);
  while (--n >= 0) {
    T tmp(a);
    a += b;
    b = tmp;
  }
  return a;
}

int main(int argc, char **argv) {
  cout << fib(10, 1U);
}

Java

package foo;

import java.util.Iterator;

/**
 * the fibonacci series implemented as an Iterable.
 */
public final class Fibonacci implements Iterable<Integer> {
  /** the next and previous members of the series. */
  private int a = 1, b = 1;

  @Override
  public Iterator<Integer> iterator() {
    return new Iterator<Integer>() {
      /** the series is infinite. */
      public boolean hasNext() { return true; }
      public Integer next() {
        int tmp = a;
        a += b;
        b = tmp;
        return a;
      }
      public void remove() { throw new UnsupportedOperationException(); }
    };
  }

  /**
   * the n<sup>th</sup> element of the given series.
   * @throws NoSuchElementException if there are less than n elements in the
   *   given Iterable's {@link Iterable#iterator iterator}.
   */
  public static <T>
  T nth(int n, Iterable<T> iterable) {
    Iterator<? extends T> it = iterable.iterator();
    while (--n > 0) {
      it.next();
    }
    return it.next();
  }

  public static void main(String[] args) {
    System.out.print(nth(10, new Fibonacci()));
  }
}

Java w/ language specified(first line shown is line 12)

package foo;

import java.util.Iterator;

/**
 * the fibonacci series implemented as an Iterable.
 */
public final class Fibonacci implements Iterable<Integer> {
  /** the next and previous members of the series. */
  private int a = 1, b = 1;

  @Override
  public Iterator<Integer> iterator() {
    return new Iterator<Integer>() {
      /** the series is infinite. */
      public boolean hasNext() { return true; }
      public Integer next() {
        int tmp = a;
        a += b;
        b = tmp;
        return a;
      }
      public void remove() { throw new UnsupportedOperationException(); }
    };
  }

  /**
   * the n<sup>th</sup> element of the given series.
   * @throws NoSuchElementException if there are less than n elements in the
   *   given Iterable's {@link Iterable#iterator iterator}.
   */
  public static <T>
  T nth(int n, Iterable<T> iterable) {
    Iterator<? extends T> in = iterable.iterator();
    while (--n > 0) {
      in.next();
    }
    return in.next();
  }

  public static void main(String[] args) {
    System.out.print(nth(10, new Fibonacci()));
  }
}

# not a java comment
# not keywords: static_cast and namespace

Javascript

/**
 * nth element in the fibonacci series.
 * @param n >= 0
 * @return the nth element, >= 0.
 */
function fib(n) {
  var a = 1, b = 1;
  var tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}

document.write(fib(10));

Issue 12 - Javascript Regular Expressions

/foo/;  // a slash starting a line treated as a regexp beginning
"foo".match(/fo+$/);
// this line comment not treated as a regular expressions
"foo /bar/".test(/"baz"/);  // test string and regexp boundaries
var division = /\b\d+\/\d+/g;  // test char sets and escaping of specials
var allSpecials = /([^\(\)\[\]\{\}\-\?\+\*\.\^\$\/]+)\\/;
var slashInCharset = /[^/]/g, notCloseSq = /[^\]]/;

// test that slash used in numeric context treated as an operator
1 / 2;
1. / x;
x / y;
(x) / y;
1 /* foo */ / 2;
1 /* foo *// 2;
1/2;
1./x;
x/y;
(x)/y;

// test split over two lines.  line comment should not fool it
1//
/2;

x++/y;
x--/y;
x[y] / z;
f() / n;

// test that slash after non postfix operator is start of regexp
log('matches = ' + /foo/.test(foo));

// test keyword preceders
return /a regexp/;
division = notreturn / not_a_regexp / 2;  // keyword suffix does not match

// & not used as prefix operator in javascript but this should still work
&/foo/;

extends = /extends/;

Issue 12 - Javascript Regular Expressions w/ language specified

/foo/;  // a slash starting a line treated as a regexp beginning
"foo".match(/fo+$/);
// this line comment not treated as a regular expressions
"foo /bar/".test(/"baz"/);  // test string and regexp boundaries
var division = /\b\d+\/\d+/g;  // test char sets and escaping of specials
var allSpecials = /([^\(\)\[\]\{\}\-\?\+\*\.\^\$\/]+)\\/;
var slashInCharset = /[^/]/g, notCloseSq = /[^\]]/;

// test that slash used in numeric context treated as an operator
1 / 2;
1. / x;
x / y;
(x) / y;
1 /* foo */ / 2;
1 /* foo *// 2;
1/2;
1./x;
x/y;
(x)/y;

// test split over two lines.  line comment should not fool it
1//
/2;

x++/y;
x--/y;
x[y] / z;
f() / n;

// test that slash after non postfix operator is start of regexp
log('matches = ' + /foo/.test(foo));

// test keyword preceders
return /a regexp/;
division = notreturn / not_a_regexp / 2;  // keyword suffix does not match

// & not used as prefix operator in javascript but this should still work
&/foo/;

extends = /extends/;

Coffee

class Animal
  constructor: (@name) ->
  move: (meters, loc) ->
    alert @name + " moved " + meters + "m."
  travel: (path...) ->
    for place in path
      @move place.distance, place.location

class Horse extends Animal
  ###
  @param name Horse name
  @param jumper Jumping ability
  ###
  constructor: (name, jumper) ->
    super name
    @capable = jumper
  step: ->
    alert '''
          Step,
          step...
          '''
  jump: ->
    @capable
  move: (meters, where) ->
    switch where
      when "ground"
        @step()
        super meters
      when "hurdle"
        super meters if @jump()

# Create horse
tom = new Horse "Tommy", yes

street =
  location: "ground"
  distance: 12
car =
  location: "hurdle"
  distance: 2

###
Tell him to travel:
1. through the street
2. over the car
###
tom.travel street, car

Perl

#!/usr/bin/perl

use strict;
use integer;

# the nth element of the fibonacci series
# param n - an int >= 0
# return an int >= 0
sub fib($) {
  my $n = shift, $a = 1, $b = 1;
  ($a, $b) = ($a + $b, $a) until (--$n < 0);
  return $a;
}

print fib(10);

Python

#!/usr/bin/python2.4

def fib():
  '''
  a generator that produces the elements of the fibonacci series
  '''

  a = 1
  b = 1
  while True:
    a, b = a + b, a
    yield a

def nth(series, n):
  '''
  returns the nth element of a series,
  consuming the earlier elements of the series
  '''

  for x in series:
    n = n - 1
    if n <= 0: return x

print nth(fib(), 10)

Python w/ language specified

#!/usr/bin/python2.4

def fib():
  '''
  a generator that produces the fibonacci series's elements
  '''

  a = 1
  b = 1
  while True:
    a, b = a + b, a
    yield a

def nth(series, n):
  '''
  returns the nth element of a series,
  consuming the series' earlier elements.
  '''

  for x in series:
    n -= 1
    if n <= 0: return x

print nth(fib(), 10)

/* not a comment and not keywords: null char true */

SQL w/ language specified

/* A multi-line
 * comment */
'Another string /* Isn\'t a comment',
"A string */"
-- A line comment
SELECT * FROM users WHERE id IN (1, 2.0, +30e-1);
-- keywords are case-insensitive.
-- Note: user-table is a single identifier, not a pair of keywords
select * from user-table where id in (x, y, z);

XML

<!DOCTYPE series PUBLIC "fibonacci numbers">

<series.root base="1" step="s(n-2) + s(n-1)">
  <element i="0">1</element>
  <element i="1">1</element>
  <element i="2">2</element>
  <element i="3">3</element>
  <element i="4">5</element>
  <element i="5">8</element>
  ...
</series.root>

HTML

<html>
  <head>
    <title>Fibonacci number</title>
    <style><!-- BODY { text-decoration: blink } --></style>
    <script src="foo.js"></script>
    <script src="bar.js"></script>
  </head>
  <body>
    <noscript>
      <dl>
        <dt>Fibonacci numbers</dt>
        <dd>1</dd>
        <dd>1</dd>
        <dd>2</dd>
        <dd>3</dd>
        <dd>5</dd>
        <dd>8</dd>
        &hellip;
      </dl>
    </noscript>

    <script type="text/javascript"><!--
function fib(n) {
  var a = 1, b = 1;
  var tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}

document.writeln(fib(10));
// -->
    </script>
  </body>
</html>

HTML w/ language specified

Fibonacci Numbers

<noscript>
  <dl style="list-style: disc">
    <dt>Fibonacci numbers</dt>
    <dd>1</dd>
    <dd>1</dd>
    <dd>2</dd>
    <dd>3</dd>
    <dd>5</dd>
    <dd>8</dd>
    &hellip;
  </dl>
</noscript>

<script type="text/javascript"><!--
function fib(n) {
  var a = 1, b = 1;
  var tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}

document.writeln(fib(10));
// -->
</script>

HTML using XMP

<html> <head> <title>Fibonacci number</title> </head> <body> <noscript> <dl> <dt>Fibonacci numbers</dt> <dd>1</dd> <dd>1</dd> <dd>2</dd> <dd>3</dd> <dd>5</dd> <dd>8</dd> &hellip; </dl> </noscript> <script type="text/javascript"><!-- function fib(n) { var a = 1, b = 1; var tmp; while (--n >= 0) { tmp = a; a += b; b = tmp; } return a; } document.writeln(fib(10)); // --> </script> </body> </html>

XHTML

<xhtml>
  <head>
    <title>Fibonacci number</title>
  </head>
  <body onload="alert(fib(10))">
    <script type="text/javascript"><![CDATA[
function fib(n) {
  var a = 1, b = 1;
  var tmp;
  while (--n >= 0) {
    tmp = a;
    a += b;
    b = tmp;
  }
  return a;
}
]]>
    </script>
  </body>
</xhtml>

PHP

<html>
  <head>
    <title><?= 'Fibonacci numbers' ?></title>

    <?php
      // PHP has a plethora of comment types
      /* What is a
         "plethora"? */
      function fib($n) {
        # I don't know.
        $a = 1;
        $b = 1;
        while (--$n >= 0) {
          echo "$a\n";
          $tmp = $a;
          $a += $b;
          $b = $tmp;
        }
      }
    ?>
  </head>
  <body>
    <?= fib(10) ?>
  </body>
</html>

XSL (Issue 19)

<!-- Test elements and attributes with namespaces -->

<xsl:stylesheet xml:lang="en">
  <xsl:template match=".">
    <xsl:text>Hello World</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Whitespace



Misc

// ends with line comment token
//

User submitted testcase for Bug 4

Javascript Snippets wrapped in HTML SCRIPT tags hides/destroys inner content

<script type="text/javascript">
   var savedTarget=null;                           // The target layer (effectively vidPane)
   var orgCursor=null;                             // The original mouse style so we can restore it
   var dragOK=false;                               // True if we're allowed to move the element under mouse
   var dragXoffset=0;                              // How much we've moved the element on the horozontal
   var dragYoffset=0;                              // How much we've moved the element on the verticle
   vidPaneID = document.getElementById('vidPane'); // Our movable layer
   vidPaneID.style.top='75px';                     // Starting location horozontal
   vidPaneID.style.left='75px';                    // Starting location verticle
<script>

The fact that the script tag was not closed properly was causing PR_splitSourceNodes to end without emitting the script contents.

Bug 8 - tabs mangled

If tabs are used to indent code inside <pre> IE6 and 7 won't honor them after the script runs. Code indented with tabs will be shown aligned to the left margin instead of the proper indenting shown in Firefox. I'm using Revision 20 of prettify.js, IE 6.0.29.00 in English and IE 7.0.5730.11 in Spanish.

one	Two	three	Four	five	|
Six	seven	Eight	nine	Ten	|
eleven	Twelve	thirteen	Fourteen	fifteen	|

Bug 14a - does not recognize <br> as newline

//comment
int main(int argc, char **argv) {}

Bug 14b - comments not ignored

<!-- There's an HTML comment in my comment -->
<p>And another one inside the end tag</p>

Bug 20 - missing blank lines

<html>

<head>

Bug 21 - code doesn't copy and paste well in IE

<html>
  <head>
    <title>Test</title>
  </head>
</html>

To test this bug, disable overriding of _pr_isIE6 in test_base.js by putting #testcopypaste on the end of the URL and reloading the page, then copy and paste the above into Notepad.

Bug 22 - Line numbers and other non-code spans in code

01: // This is a line of code
02: /* Multiline comments can
03:  * span over and around
04:  * line markers
And can even be interrupted
by inline code annotations
05:  */
06: class MyClass extends Foo {
07:   public static void main(String... argv) {
08:     System.out.print("Hello World");
09:   }
10: }

Bug 24 - Lua Syntax Highlighting

os=require("os")
math=require("math")

-- Examples from the language reference
     a = 'alo\n123"'
     a = "alo\n123\""
     a = '\97lo\10\04923"'
     a = [[alo
     123"]]
     a = [==[
     alo
     123"]==]

3   3.0   3.1416   314.16e-2   0.31416E1   0xff   0x56

-- Some comments that demonstrate long brackets
double_quoted = "Not a long bracket [=["
--[=[ quoting out
 [[ foo ]]
 [==[does not end comment either]==]
]=]
past_end_of_comment
--]=]

-- Example code courtesy Joseph Harmbruster
#
do
  local function ssgeneral(t, n, before)
    for _, h in ipairs(incs) do
      for i = h + 1, n do
        local v = t[i]
        for j = i - h, 1, -h do
          local testval = t[j]
          if not before(v, testval) then break end
          t[i] = testval; i = j
        end
        t[i] = v
      end 
    end
    return t
  end

  function shellsort(t, before, n)
    n = n or #t
    if not before or before == "<" then return ssup(t, n)
    elseif before == ">" then return ssdown(t, n)
    else return ssgeneral(t, n, before)
    end
  end
  return shellsort
end

Bug 27 - VBScript w/ language specified

Imports System

Class [class]
    Shared Sub [shared](ByVal [boolean] As Boolean)
        If [boolean] Then
            Console.WriteLine("true")
        Else
            Console.WriteLine("false")
        End If
    End Sub
End Class

' Comment
‘ Second Line comment with a smart quote _
  continued line using VB6 syntax.
Module [module]
    Sub Main()
        [class].[shared](True)

        ' This prints out: ".
        Console.WriteLine("""")

        ' This prints out: a"b.
        Console.WriteLine("a""b")

        ' This prints out: a.
        Console.WriteLine("a"c)

        ' This prints out: ".
        Console.WriteLine(""""c)

        REM an old-style comment
        REMOVE(not_a_comment)
    End Sub
End Module

Dim d As Date
d = # 8/23/1970 3:45:39AM #
d = # 8/23/1970 #
d = # 3:45:39AM #
d = # 3:45:39 #
d = # 13:45:39 #
d = # 13:45:39PM #

Dim n As Float
n = (0.0, .99F, 1.0E-2D, 1.0E+3D, .5E4, 1E3R, 4D)

Dim i As Integer
i = (0, 123, 45L, &HA0I, &O177S)

Bug 30 - Haskell w/ language specified

-- A comment
Not(--"a comment")
Also.not(--(A.comment))

module Foo(bar) where
import Blah
import BlahBlah(blah)
import Monads(Exception(..), FIO(..),unFIO,handle,runFIO,fixFIO,fio,
              write,writeln,HasNext(..),HasOutput(..))

{- nested comments
 - don't work {-yet-} -}
instance Thingy Foo where
  a = b

data Foo :: (* -> * -> *) -> * > * -> * where
  Nil :: Foo a b c
  Cons :: a b c -> Foo abc -> Foo a b c

str = "Foo\\Bar"
char = 'x'
Not.A.Char = 'too long'  -- Don't barf.  Show that 't is a lexical error.

(ident, ident', Fo''o.b'ar)

(0, 12, 0x45, 0xA7, 0o177, 0O377, 0.1, 1.0, 1e3, 0.5E-3, 1.0E+45)

Bug 33 - OCaml and F#

(*
 * Print the 10th fibonacci number
 *)

//// A line comment
"A string";;
(0, 125, 0xa0, -1.0, 1e6, 1.2e-3);;  // number literals

#if fibby
  let
    rec fib = function (0, a, _) -> a
                     | (n, a, b) -> fib(n - 1, a + b, a)
  in
    print_int(fib(10, 1, 1));;
#endif

let zed = 'z'

let f' x' = x' + 1

Still TODO: handle nested (* (* comments *) *) properly.

Bug 42 - Lisp Syntax Highlighting

; -*- mode: lisp -*-

(defun back-six-lines () (interactive) (forward-line -6))
(defun forward-six-lines () (interactive) (forward-line 6))

(global-set-key "\M-l" 'goto-line)
(global-set-key "\C-z" 'advertised-undo)
(global-set-key [C-insert] 'clipboard-kill-ring-save)
(global-set-key [S-insert] 'clipboard-yank)
(global-set-key [C-up] 'back-six-lines)
(global-set-key [C-down] 'forward-six-lines)

(setq visible-bell t)
(setq user-mail-address "foo@bar.com")
(setq default-major-mode 'text-mode)

(setenv "TERM" "emacs")
(c-set-offset 'case-label 2)
(setq c-basic-offset 2)
(setq perl-indent-level 0x2)
(setq delete-key-deletes-forward t)
(setq indent-tabs-mode nil)

;; Text mode
(add-hook 'text-mode-hook 
  '(lambda ()
     (turn-on-auto-fill)
   )
)

;; Fundamental mode
(add-hook 'fundamental-mode-hook 
  '(lambda ()
     (turn-on-auto-fill)
   )
)

;; Define and cond are keywords in scheme
(define (sqt x) (sqrt-iter 1.0 2.0 x))

Bug 45 - Square brackets in strings

throw new RuntimeException("Element [" + element.getName() + 
  "] missing attribute.");
variable++;

Protocol Buffers

message SearchRequest {
  required string query = 1;
  optional int32 page_number = 2;
  optional int32 result_per_page = 3 [default = 10];
  enum Corpus {
    UNIVERSAL = 0;
    WEB = 1;
    IMAGES = 2;
    LOCAL = 3;
    NEWS = 4;
    PRODUCTS = 5;
    VIDEO = 6;
  }
  optional Corpus corpus = 4 [default = UNIVERSAL];
}

Wiki syntax w/ language specified

#summary hello world
#labels HelloWorld WikiWord Hiya

[http://www.google.com/?q=WikiSyntax+site:code.google.com WikiSyntax]

Lorem Ipsum `while (1) print("blah blah");`

   * Bullet
   * Points
      * NestedBullet

==DroningOnAndOn==
{{{
  // Some EmbeddedSourceCode
  void main() {
    Print('hello world');
  }
}}}

{{{
  <!-- Embedded XML -->
  <foo bar="baz"><boo /><foo>
}}}

CSS w/ language specified

<!--
@charset('UTF-8');

/** A url that is not quoted. */
@import(url(/more-styles.css));

HTML { content-before: 'hello\20'; content-after: 'w\6f rld';
       -moz-spiff: inherit !important }

/* Test units on numbers. */
BODY { margin-bottom: 4px; margin-left: 3in; margin-bottom: 0; margin-top: 5% }

/** Test number literals and quoted values. */
TABLE.foo TR.bar A#visited { color: #001123; font-family: "monospace" }
/** bolder is not a name, so should be plain.  !IMPORTANT is a keyword
  * regardless of case.
  */
blink { text-decoration: BLINK !IMPORTANT; font-weight: bolder }
/* Empty url() was causing infinite recursion */
a { background-image: url(); }
p#featured{background:#fea}
-->

Issue 79 CSS highlighting

<style type='text/css'>
/* desert scheme ported from vim to google prettify */
code.prettyprint { display: block; padding: 2px; border: 1px solid #888;
background-color: #333; }
.str { color: #ffa0a0; } /* string  - pink */
.kwd { color: #f0e68c; font-weight: bold; }
.com { color: #87ceeb; } /* comment - skyblue */
.typ { color: #98fb98; } /* type    - lightgreen */
.lit { color: #cd5c5c; } /* literal - darkred */
.pun { color: #fff; }    /* punctuation */
.pln { color: #fff; }    /* plaintext */
.tag { color: #f0e68c; font-weight: bold; } /* html/xml tag    - lightyellow*/
.atn { color: #bdb76b; font-weight: bold; } /* attribute name  - khaki*/
.atv { color: #ffa0a0; } /* attribute value - pink */
.dec { color: #98fb98; } /* decimal         - lightgreen */
</style>

Issue 84 NBSPs

super("&nbsp;");

Issue 86

#One Two words

#One Two lines

#One
Two lines
#One
Two lines
#One Two lines

#One
Two lines

Issue 92 -- capital letters in tag names

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark>
    <name>Simple placemark</name>
    <description Lang="en">Attached to the ground. Intelligently places itself 
       at the height of the underlying terrain.</description>
    <Point>
      <coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
    </Point>
  </Placemark>
</kml>

Issue 93 -- C# verbatim strings

// The normal string syntax
string a = "C:\\";
// is equivalent to a verbatim string
string b = @"C:\";

VHDL mode

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

-- A line comment
entity foo_entity is

  generic (-- comment after punc
    a : natural := 42;
    x : real := 16#ab.cd#-3
  );
  port (
    clk_i : in  std_logic;
    b_i   : in  natural range 0 to 100;
    c_o   : out std_logic_vector(5 downto 0);
    \a "name"\ : out integer  -- extended identifier
  );

end entity foo_entity;

architecture foo_architecture of foo_entity is
  signal bar_s : std_logic_vector(2 downto 0);
begin
  
  bar_s <= b"101";

  dummy_p : process (clk_i)
  begin
    if b_i = 1 then
      c_o <= (others => '0');
    elsif rising_edge(clk_i) then
      c_o <= "1011" & bar_s(1 downto 0);
    end if;
  end process dummy_p;

end architecture foo_architecture;

YAML mode

application: mirah-lang
version: 1

# Here's a comment
handlers:
  - url: /red/*
     servlet: mysite.server.TeamServlet
     init_params:
       teamColor: red
       bgColor: "#CC0000"
     name: redteam
  - url: /blue/*
     servlet: mysite.server.TeamServlet
     init_params:
       teamColor: blue
       bgColor: "#0000CC"
     name: blueteam
  - url: /register/*
     jsp: /register/start.jsp
  - url: *.special
     filter: mysite.server.LogFilterImpl
     init_params:
       logType: special
  
%YAML 1.1
---
!!map {
  ? !!str ""
  : !!str "value",
  ? !!str "explicit key"
  : !!str "value",
  ? !!str "simple key"
  : !!str "value",
  ? !!seq [
    !!str "collection",
    !!str "simple",
    !!str "key"
  ]
  : !!str "value"
}

Scala mode

/* comment 1 */
/*
comment 2
*/
/* comment / * comment 3 **/
// strings
"Hello, World!", "\n",
`an-identifier`, `\n`,
'A', '\n',
'aSymbol,
"""Hello,
World""", """Hello,\nWorld""",
"""Hello, "World"!""",
"""Hello, \"World\""""

// Numbers
0
0123
0xa0
0XA0L
123
123.45
1.50F
0.50
.50
123e-1
123.45e+1
1.50e2
0.50e-6
.50e+42f

// Values
false, true, null, this;

// Keywords
class MyClass;
import foo.bar;
package baz;

// From scala-lang.org/node/242
def act() {
  var pongCount = 0
  loop {
    react {
      case Ping =>
        if (pongCount % 1000 == 0)
          Console.println("Pong: ping "+pongCount)
        sender ! Pong
        pongCount = pongCount + 1
      case Stop =>
        Console.println("Pong: stop")
        exit()
    }
  }
}

Go mode

package main  /* Package of which this program is part. */

import fmt "fmt"  // Package implementing formatted I/O.


func main() {
    fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n")  // Semicolon inserted here
}

/* " */  "foo /* "  /*/  */
/* ` */  `foo /* `  /*/  */

Erlang mode

% Sample comment

-module(my_test).
-include_lib("my_sample_lib.hrl").
-export([
    test/2
]).

%% @doc Define a macro
-define(my_macro, Variable).

%% @doc My function
test(Variables, MoreVariables) ->
    % Inline comment
    {ok,Scanned,_} = my_lib:do_stuff(),

    Variable = fun(V) -> {ok, V} end,

    try ?my_macro({value, test}) of
        {value, Result, _} ->
            {ok, Result}
    catch
        Type:Error ->
            {'error', Type, Error}
    end.
Test IE by copy/pasting content here. prettify-2013.03.04/tests/test_base.js0000640000175000017500000001770512115200050016055 0ustar domidomi// get accurate timing. // This file must be loaded after prettify.js for this to work. PR_SHOULD_USE_CONTINUATION = false; var attribToHtml, textToHtml; var getInnerHtml; (function () { /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } var newlineRe = /[\r\n]/g; /** * Are newlines and adjacent spaces significant in the given node's innerHTML? */ function isPreformatted(node, content) { // PRE means preformatted, and is a very common case, so don't create // unnecessary computed style objects. if ('PRE' === node.tagName) { return true; } if (!newlineRe.test(content)) { return true; } // Don't care var whitespace = ''; // For disconnected nodes, IE has no currentStyle. if (node.currentStyle) { whitespace = node.currentStyle.whiteSpace; } else if (window.getComputedStyle) { // Firefox makes a best guess if node is disconnected whereas Safari // returns the empty string. whitespace = window.getComputedStyle(node, null).whiteSpace; } return !whitespace || whitespace === 'pre'; } // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = //g; var pr_quot = /\"/g; /** escapest html special characters to html. */ textToHtml = function (str) { return str.replace(pr_amp, '&') .replace(pr_lt, '<') .replace(pr_gt, '>'); }; /** like textToHtml but escapes double quotes to be attribute safe. */ attribToHtml = function (str) { return str.replace(pr_amp, '&') .replace(pr_lt, '<') .replace(pr_gt, '>') .replace(pr_quot, '"'); }; var PR_innerHtmlWorks = null; getInnerHtml = function (node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('\n')); PR_innerHtmlWorks = !/)[\r\n]+/g, '$1') .replace(/(?:[\r\n]+[ \t]*)+/g, ' '); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); }; })(); function normalizedHtml(node, out, opt_sortAttrs) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); var attrs = node.attributes; var n = attrs.length; if (n) { if (opt_sortAttrs) { var sortedAttrs = []; for (var i = n; --i >= 0;) { sortedAttrs[i] = attrs[i]; } sortedAttrs.sort(function (a, b) { return (a.name < b.name) ? -1 : a.name === b.name ? 0 : 1; }); attrs = sortedAttrs; } for (var i = 0; i < n; ++i) { var attr = attrs[i]; if (!attr.specified) { continue; } out.push(' ', attr.name.toLowerCase(), '="', attribToHtml(attr.value), '"'); } } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out, opt_sortAttrs); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } /** * @param golden a mapping from IDs of prettyprinted chunks to an abbreviated * form of the expected output. See "var goldens" in prettify_test.html * for an example. */ function go(goldens) { startClock(); prettyPrint(function () { stopClock(); runTests(goldens); }); } function runTests(goldens) { /** number of characters in common at the end up to max. */ function commonPrefix(a, b) { var n = Math.min(a.length, b.length); var i; for (i = 0; i < n; ++i) { if (a.charAt(i) !== b.charAt(i)) { break; } } return i; } /** number of characters in common at the end up to max. */ function commonSuffix(a, b, max) { var n = Math.min(a.length - max, b.length - max); var i; for (i = 0; i < n; ++i) { if (a.charAt(a.length - i - 1) !== b.charAt(b.length - i - 1)) { break; } } return i; } /** convert a plain text string to html by escaping html special chars. */ function html(plainText) { return attribToHtml(plainText).replace(/\xa0/g, ' '); } /** * get normalized markup. innerHTML varies enough across browsers that we * can't use it. */ function normalizedInnerHtml(node) { var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out, true); } out = out.join(''); // more normalization to work around problems with non-ascii chars in // regexps in Safari for (var i = 0; (i = out.indexOf('\xa0')) >= 0;) { out = out.substring(0, i) + ' ' + out.substring(i + 1); } return out.replace(/\r\n?/g, '\n'); } var htmlOut = []; var failures = 0; document.getElementById('errorReport').innerHTML = '

Running tests…<\/h1>'; htmlOut.push('

Test results<\/h1>'); for (var lang in goldens) { var container = document.getElementById(lang); // Convert abbreviations that start with `. var golden = goldens[lang].replace(/`([A-Z]{3})/g, function (_, lbl) { return (lbl == 'END' ? '<\/span>' : ''); }) // Line numbers .replace(/`#(?![0-9])/, '
  • ') .replace(/`#([0-9])/g, '
  • '); var actual = normalizedInnerHtml(container); if (golden !== actual) { // test failed // write out var pre = commonPrefix(golden, actual); var post = commonSuffix(golden, actual, pre); ++failures; htmlOut.push( '

    ' + html(lang) + '<\/a> Failed<\/h2>'); htmlOut.push( '' + html(golden.substring(0, pre)) + '»' + html(golden.substring(pre, golden.length - post)) + '<\/span>«' + html(golden.substring(golden.length - post)) + '
    !==
    ' + html(actual.substring(0, pre)) + '»' + html(actual.substring(pre, actual.length - post)) + '<\/span>«' + html(actual.substring(actual.length - post)) + '<\/tt>'); } else { htmlOut.push( '

    ' + html(lang) + '<\/a> OK<\/h2>'); } } var summary = ( failures ? (failures + ' test' + (failures === 1 ? '' : 's') + ' failed') : 'Tests Passed'); var summaryStr = '

    ' + summary + '<\/h2>'; htmlOut.push(summaryStr); htmlOut.splice(0, 0, summaryStr); document.title += ' \u2014 ' + summary; document.getElementById('errorReport').innerHTML = htmlOut.join('').replace(/<br>/g, '<br>\n'); } var startTime = null; function startClock() { startTime = (new Date).getTime(); } function stopClock() { var delta = (new Date).getTime() - startTime; startTime = null; document.getElementById('timing').innerHTML = 'Took ' + delta + ' ms'; } prettify-2013.03.04/tests/test_styles.css0000640000175000017500000000036712115200050016636 0ustar domidomi/* Used by error reporting code in test_base.js */ .mismatch { background: #fee; font-weight: bold } span.annot { margin:2px 2px 2px 3em; border:1px dotted #88f; background:#eef; padding: 0 2px 0 2px } .nocode { background: #f8f8f8 } prettify-2013.03.04/tests/debug-ie-compat-matrix.html0000640000175000017500000000564012115200050020673 0ustar domidomi one short line,
    one giant leap for cross-browser compatibility
    two turtledoves a partridge in a pear tree zero fencepost errors

    prettify-2013.03.04/tests/ie-newline-copy-paste.html0000640000175000017500000001065112115200050020543 0ustar domidomiIE Newline Copy/Paste Info Gathering

    I'm trying to squash, once and for all, the problems with newlines in <PRE>s in IE. I can't run 3 versions of IE, so I'd really appreciate any help from people who have IE open and running.

    Please copy from START through END below and paste it into the textarea below. Then hit Ctrl-A, Ctrl-C to copy the textarea contents, and paste that into an email. Please also copy and paste the RESULTS section below and include it in the email response as well and send it to me or respond to the discussion list.

    In case you're interested, there are two problems: choosing a way to split lines that doesn't introduce too few or extra newlines, and a way to make sure that the resulting code can be copy-pasted into a plain text editors such as the textarea below. This is my attempt to gather information on both issues by IE version.

    cheers.

    START

    before
    [Not generated via innerHTML CR]
    after
    before
    [Not generated via innerHTML BR]
    after
    before
    [Not generated via innerHTML CR + BR]
    after
    before
    
    [Not generated via innerHTML BR + CR]
    after

    END

    one
    two
    three

    RESULTS

    TEXTAREA

    prettify-2013.03.04/tests/run_prettify_test.html0000640000175000017500000000272412115200050020220 0ustar domidomi Run_Prettify Test
    <div style="color: #f00">
      Hello, World!
    </div>
    
    prettify-2013.03.04/src/0000751000175000017500000000000012362767251013212 5ustar domidomiprettify-2013.03.04/src/lang-css.js0000640000175000017500000001404712115200050015234 0ustar domidomi// Copyright (C) 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for CSS. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like *
    
     *
     *
     * http://www.w3.org/TR/CSS21/grammar.html Section G2 defines the lexical
     * grammar.  This scheme does not recognize keywords containing escapes.
     *
     * @author mikesamuel@gmail.com
     */
    
    // This file is a call to a function defined in prettify.js which defines a
    // lexical scanner for CSS and maps tokens to styles.
    
    // The call to PR['registerLangHandler'] is quoted so that Closure Compiler
    // will not rename the call so that this language extensions can be
    // compiled/minified separately from one another.  Other symbols defined in
    // prettify.js are similarly quoted.
    
    // The call is structured thus:
    // PR['registerLangHandler'](
    //    PR['createSimpleLexer'](
    //        shortcutPatterns,
    //        fallThroughPatterns),
    //    [languageId0, ..., languageIdN])
    
    // Langugage IDs
    // =============
    // The language IDs are typically the file extensions of source files for
    // that language so that users can syntax highlight arbitrary files based
    // on just the extension.  This is heuristic, but works pretty well in
    // practice.
    
    // Patterns
    // ========
    // Lexers are typically implemented as a set of regular expressions.
    // The SimpleLexer function takes regular expressions, styles, and some
    // pragma-info and produces a lexer.  A token description looks like
    //   [STYLE_NAME, /regular-expression/, pragmas]
    
    // Initially, simple lexer's inner loop looked like:
    
    //    while sourceCode is not empty:
    //      try each regular expression in order until one matches
    //      remove the matched portion from sourceCode
    
    // This was really slow for large files because some JS interpreters
    // do a buffer copy on the matched portion which is O(n*n)
    
    // The current loop now looks like
    
    //    1. use js-modules/combinePrefixPatterns.js to 
    //       combine all regular expressions into one 
    //    2. use a single global regular expresion match to extract all tokens
    //    3. for each token try regular expressions in order until one matches it
    //       and classify it using the associated style
    
    // This is a lot more efficient but it does mean that lookahead and lookbehind
    // can't be used across boundaries to classify tokens.
    
    // Sometimes we need lookahead and lookbehind and sometimes we want to handle
    // embedded language -- JavaScript or CSS embedded in HTML, or inline assembly
    // in C.
    
    // If a particular pattern has a numbered group, and its style pattern starts
    // with "lang-" as in
    //    ['lang-js', /}
         * 
  • define style rules. See the example page for examples. *
  • mark the {@code
    } and {@code } tags in your source with
         *    {@code class=prettyprint.}
         *    You can also use the (html deprecated) {@code } tag, but the pretty
         *    printer needs to do more substantial DOM manipulations to support that, so
         *    some css styles may not be preserved.
         * </ol>
         * That's it.  I wanted to keep the API as simple as possible, so there's no
         * need to specify which language the code is in, but if you wish, you can add
         * another class to the {@code <pre>} or {@code <code>} element to specify the
         * language, as in {@code <pre class="prettyprint lang-java">}.  Any class that
         * starts with "lang-" followed by a file extension, specifies the file type.
         * See the "lang-*.js" files in this directory for code that implements
         * per-language file handlers.
         * <p>
         * Change log:<br>
         * cbeust, 2006/08/22
         * <blockquote>
         *   Java annotations (start with "@") are now captured as literals ("lit")
         * </blockquote>
         * @requires console
         */
        
        // JSLint declarations
        /*global console, document, navigator, setTimeout, window, define */
        
        /**
         * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
         * UI events.
         * If set to {@code false}, {@code prettyPrint()} is synchronous.
         */
        window['PR_SHOULD_USE_CONTINUATION'] = true;
        
        /**
         * Pretty print a chunk of code.
         * @param {string} sourceCodeHtml The HTML to pretty print.
         * @param {string} opt_langExtension The language name to use.
         *     Typically, a filename extension like 'cpp' or 'java'.
         * @param {number|boolean} opt_numberLines True to number lines,
         *     or the 1-indexed number of the first line in sourceCodeHtml.
         * @return {string} code as html, but prettier
         */
        var prettyPrintOne;
        /**
         * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
         * {@code class=prettyprint} and prettify them.
         *
         * @param {Function} opt_whenDone called when prettifying is done.
         * @param {HTMLElement|HTMLDocument} opt_root an element or document
         *   containing all the elements to pretty print.
         *   Defaults to {@code document.body}.
         */
        var prettyPrint;
        
        
        (function () {
          var win = window;
          // Keyword lists for various languages.
          // We use things that coerce to strings to make them compact when minified
          // and to defeat aggressive optimizers that fold large string constants.
          var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
          var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," + 
              "double,enum,extern,float,goto,inline,int,long,register,short,signed," +
              "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
          var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
              "new,operator,private,protected,public,this,throw,true,try,typeof"];
          var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
              "concept,concept_map,const_cast,constexpr,decltype,delegate," +
              "dynamic_cast,explicit,export,friend,generic,late_check," +
              "mutable,namespace,nullptr,property,reinterpret_cast,static_assert," +
              "static_cast,template,typeid,typename,using,virtual,where"];
          var JAVA_KEYWORDS = [COMMON_KEYWORDS,
              "abstract,assert,boolean,byte,extends,final,finally,implements,import," +
              "instanceof,interface,null,native,package,strictfp,super,synchronized," +
              "throws,transient"];
          var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
              "as,base,by,checked,decimal,delegate,descending,dynamic,event," +
              "fixed,foreach,from,group,implicit,in,internal,into,is,let," +
              "lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
              "sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
              "var,virtual,where"];
          var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
              "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
              "throw,true,try,unless,until,when,while,yes";
          var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
              "debugger,eval,export,function,get,null,set,undefined,var,with," +
              "Infinity,NaN"];
          var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
              "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
              "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
          var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
              "elif,except,exec,finally,from,global,import,in,is,lambda," +
              "nonlocal,not,or,pass,print,raise,try,with,yield," +
              "False,True,None"];
          var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
              "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
              "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
              "BEGIN,END"];
           var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," +
              "enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," +
              "pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"];
          var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
              "function,in,local,set,then,until"];
          var ALL_KEYWORDS = [
              CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
              PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
          var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
        
          // token style names.  correspond to css classes
          /**
           * token style for a string literal
           * @const
           */
          var PR_STRING = 'str';
          /**
           * token style for a keyword
           * @const
           */
          var PR_KEYWORD = 'kwd';
          /**
           * token style for a comment
           * @const
           */
          var PR_COMMENT = 'com';
          /**
           * token style for a type
           * @const
           */
          var PR_TYPE = 'typ';
          /**
           * token style for a literal value.  e.g. 1, null, true.
           * @const
           */
          var PR_LITERAL = 'lit';
          /**
           * token style for a punctuation string.
           * @const
           */
          var PR_PUNCTUATION = 'pun';
          /**
           * token style for plain text.
           * @const
           */
          var PR_PLAIN = 'pln';
        
          /**
           * token style for an sgml tag.
           * @const
           */
          var PR_TAG = 'tag';
          /**
           * token style for a markup declaration such as a DOCTYPE.
           * @const
           */
          var PR_DECLARATION = 'dec';
          /**
           * token style for embedded source.
           * @const
           */
          var PR_SOURCE = 'src';
          /**
           * token style for an sgml attribute name.
           * @const
           */
          var PR_ATTRIB_NAME = 'atn';
          /**
           * token style for an sgml attribute value.
           * @const
           */
          var PR_ATTRIB_VALUE = 'atv';
        
          /**
           * A class that indicates a section of markup that is not code, e.g. to allow
           * embedding of line numbers within code listings.
           * @const
           */
          var PR_NOCODE = 'nocode';
        
          
          
          /**
           * A set of tokens that can precede a regular expression literal in
           * javascript
           * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
           * has the full list, but I've removed ones that might be problematic when
           * seen in languages that don't support regular expression literals.
           *
           * <p>Specifically, I've removed any keywords that can't precede a regexp
           * literal in a syntactically legal javascript program, and I've removed the
           * "in" keyword since it's not a keyword in many languages, and might be used
           * as a count of inches.
           *
           * <p>The link above does not accurately describe EcmaScript rules since
           * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
           * very well in practice.
           *
           * @private
           * @const
           */
          var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
          
          // CAVEAT: this does not properly handle the case where a regular
          // expression immediately follows another since a regular expression may
          // have flags for case-sensitivity and the like.  Having regexp tokens
          // adjacent is not valid in any language I'm aware of, so I'm punting.
          // TODO: maybe style special characters inside a regexp as punctuation.
        
          /**
           * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
           * matches the union of the sets of strings matched by the input RegExp.
           * Since it matches globally, if the input strings have a start-of-input
           * anchor (/^.../), it is ignored for the purposes of unioning.
           * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
           * @return {RegExp} a global regex.
           */
          function combinePrefixPatterns(regexs) {
            var capturedGroupIndex = 0;
          
            var needToFoldCase = false;
            var ignoreCase = false;
            for (var i = 0, n = regexs.length; i < n; ++i) {
              var regex = regexs[i];
              if (regex.ignoreCase) {
                ignoreCase = true;
              } else if (/[a-z]/i.test(regex.source.replace(
                             /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
                needToFoldCase = true;
                ignoreCase = false;
                break;
              }
            }
          
            var escapeCharToCodeUnit = {
              'b': 8,
              't': 9,
              'n': 0xa,
              'v': 0xb,
              'f': 0xc,
              'r': 0xd
            };
          
            function decodeEscape(charsetPart) {
              var cc0 = charsetPart.charCodeAt(0);
              if (cc0 !== 92 /* \\ */) {
                return cc0;
              }
              var c1 = charsetPart.charAt(1);
              cc0 = escapeCharToCodeUnit[c1];
              if (cc0) {
                return cc0;
              } else if ('0' <= c1 && c1 <= '7') {
                return parseInt(charsetPart.substring(1), 8);
              } else if (c1 === 'u' || c1 === 'x') {
                return parseInt(charsetPart.substring(2), 16);
              } else {
                return charsetPart.charCodeAt(1);
              }
            }
          
            function encodeEscape(charCode) {
              if (charCode < 0x20) {
                return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
              }
              var ch = String.fromCharCode(charCode);
              return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
                  ? "\\" + ch : ch;
            }
          
            function caseFoldCharset(charSet) {
              var charsetParts = charSet.substring(1, charSet.length - 1).match(
                  new RegExp(
                      '\\\\u[0-9A-Fa-f]{4}'
                      + '|\\\\x[0-9A-Fa-f]{2}'
                      + '|\\\\[0-3][0-7]{0,2}'
                      + '|\\\\[0-7]{1,2}'
                      + '|\\\\[\\s\\S]'
                      + '|-'
                      + '|[^-\\\\]',
                      'g'));
              var ranges = [];
              var inverse = charsetParts[0] === '^';
          
              var out = ['['];
              if (inverse) { out.push('^'); }
          
              for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
                var p = charsetParts[i];
                if (/\\[bdsw]/i.test(p)) {  // Don't muck with named groups.
                  out.push(p);
                } else {
                  var start = decodeEscape(p);
                  var end;
                  if (i + 2 < n && '-' === charsetParts[i + 1]) {
                    end = decodeEscape(charsetParts[i + 2]);
                    i += 2;
                  } else {
                    end = start;
                  }
                  ranges.push([start, end]);
                  // If the range might intersect letters, then expand it.
                  // This case handling is too simplistic.
                  // It does not deal with non-latin case folding.
                  // It works for latin source code identifiers though.
                  if (!(end < 65 || start > 122)) {
                    if (!(end < 65 || start > 90)) {
                      ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
                    }
                    if (!(end < 97 || start > 122)) {
                      ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
                    }
                  }
                }
              }
          
              // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
              // -> [[1, 12], [14, 14], [16, 17]]
              ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1]  - a[1]); });
              var consolidatedRanges = [];
              var lastRange = [];
              for (var i = 0; i < ranges.length; ++i) {
                var range = ranges[i];
                if (range[0] <= lastRange[1] + 1) {
                  lastRange[1] = Math.max(lastRange[1], range[1]);
                } else {
                  consolidatedRanges.push(lastRange = range);
                }
              }
          
              for (var i = 0; i < consolidatedRanges.length; ++i) {
                var range = consolidatedRanges[i];
                out.push(encodeEscape(range[0]));
                if (range[1] > range[0]) {
                  if (range[1] + 1 > range[0]) { out.push('-'); }
                  out.push(encodeEscape(range[1]));
                }
              }
              out.push(']');
              return out.join('');
            }
          
            function allowAnywhereFoldCaseAndRenumberGroups(regex) {
              // Split into character sets, escape sequences, punctuation strings
              // like ('(', '(?:', ')', '^'), and runs of characters that do not
              // include any of the above.
              var parts = regex.source.match(
                  new RegExp(
                      '(?:'
                      + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]'  // a character set
                      + '|\\\\u[A-Fa-f0-9]{4}'  // a unicode escape
                      + '|\\\\x[A-Fa-f0-9]{2}'  // a hex escape
                      + '|\\\\[0-9]+'  // a back-reference or octal escape
                      + '|\\\\[^ux0-9]'  // other escape sequence
                      + '|\\(\\?[:!=]'  // start of a non-capturing group
                      + '|[\\(\\)\\^]'  // start/end of a group, or line start
                      + '|[^\\x5B\\x5C\\(\\)\\^]+'  // run of other characters
                      + ')',
                      'g'));
              var n = parts.length;
          
              // Maps captured group numbers to the number they will occupy in
              // the output or to -1 if that has not been determined, or to
              // undefined if they need not be capturing in the output.
              var capturedGroups = [];
          
              // Walk over and identify back references to build the capturedGroups
              // mapping.
              for (var i = 0, groupIndex = 0; i < n; ++i) {
                var p = parts[i];
                if (p === '(') {
                  // groups are 1-indexed, so max group index is count of '('
                  ++groupIndex;
                } else if ('\\' === p.charAt(0)) {
                  var decimalValue = +p.substring(1);
                  if (decimalValue) {
                    if (decimalValue <= groupIndex) {
                      capturedGroups[decimalValue] = -1;
                    } else {
                      // Replace with an unambiguous escape sequence so that
                      // an octal escape sequence does not turn into a backreference
                      // to a capturing group from an earlier regex.
                      parts[i] = encodeEscape(decimalValue);
                    }
                  }
                }
              }
          
              // Renumber groups and reduce capturing groups to non-capturing groups
              // where possible.
              for (var i = 1; i < capturedGroups.length; ++i) {
                if (-1 === capturedGroups[i]) {
                  capturedGroups[i] = ++capturedGroupIndex;
                }
              }
              for (var i = 0, groupIndex = 0; i < n; ++i) {
                var p = parts[i];
                if (p === '(') {
                  ++groupIndex;
                  if (!capturedGroups[groupIndex]) {
                    parts[i] = '(?:';
                  }
                } else if ('\\' === p.charAt(0)) {
                  var decimalValue = +p.substring(1);
                  if (decimalValue && decimalValue <= groupIndex) {
                    parts[i] = '\\' + capturedGroups[decimalValue];
                  }
                }
              }
          
              // Remove any prefix anchors so that the output will match anywhere.
              // ^^ really does mean an anchored match though.
              for (var i = 0; i < n; ++i) {
                if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
              }
          
              // Expand letters to groups to handle mixing of case-sensitive and
              // case-insensitive patterns if necessary.
              if (regex.ignoreCase && needToFoldCase) {
                for (var i = 0; i < n; ++i) {
                  var p = parts[i];
                  var ch0 = p.charAt(0);
                  if (p.length >= 2 && ch0 === '[') {
                    parts[i] = caseFoldCharset(p);
                  } else if (ch0 !== '\\') {
                    // TODO: handle letters in numeric escapes.
                    parts[i] = p.replace(
                        /[a-zA-Z]/g,
                        function (ch) {
                          var cc = ch.charCodeAt(0);
                          return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
                        });
                  }
                }
              }
          
              return parts.join('');
            }
          
            var rewritten = [];
            for (var i = 0, n = regexs.length; i < n; ++i) {
              var regex = regexs[i];
              if (regex.global || regex.multiline) { throw new Error('' + regex); }
              rewritten.push(
                  '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
            }
          
            return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
          }
        
          /**
           * Split markup into a string of source code and an array mapping ranges in
           * that string to the text nodes in which they appear.
           *
           * <p>
           * The HTML DOM structure:</p>
           * <pre>
           * (Element   "p"
           *   (Element "b"
           *     (Text  "print "))       ; #1
           *   (Text    "'Hello '")      ; #2
           *   (Element "br")            ; #3
           *   (Text    "  + 'World';")) ; #4
           * </pre>
           * <p>
           * corresponds to the HTML
           * {@code <p><b>print </b>'Hello '<br>  + 'World';</p>}.</p>
           *
           * <p>
           * It will produce the output:</p>
           * <pre>
           * {
           *   sourceCode: "print 'Hello '\n  + 'World';",
           *   //                     1          2
           *   //           012345678901234 5678901234567
           *   spans: [0, #1, 6, #2, 14, #3, 15, #4]
           * }
           * </pre>
           * <p>
           * where #1 is a reference to the {@code "print "} text node above, and so
           * on for the other text nodes.
           * </p>
           *
           * <p>
           * The {@code} spans array is an array of pairs.  Even elements are the start
           * indices of substrings, and odd elements are the text nodes (or BR elements)
           * that contain the text for those substrings.
           * Substrings continue until the next index or the end of the source.
           * </p>
           *
           * @param {Node} node an HTML DOM subtree containing source-code.
           * @param {boolean} isPreformatted true if white-space in text nodes should
           *    be considered significant.
           * @return {Object} source code and the text nodes in which they occur.
           */
          function extractSourceSpans(node, isPreformatted) {
            var nocode = /(?:^|\s)nocode(?:\s|$)/;
          
            var chunks = [];
            var length = 0;
            var spans = [];
            var k = 0;
          
            function walk(node) {
              var type = node.nodeType;
              if (type == 1) {  // Element
                if (nocode.test(node.className)) { return; }
                for (var child = node.firstChild; child; child = child.nextSibling) {
                  walk(child);
                }
                var nodeName = node.nodeName.toLowerCase();
                if ('br' === nodeName || 'li' === nodeName) {
                  chunks[k] = '\n';
                  spans[k << 1] = length++;
                  spans[(k++ << 1) | 1] = node;
                }
              } else if (type == 3 || type == 4) {  // Text
                var text = node.nodeValue;
                if (text.length) {
                  if (!isPreformatted) {
                    text = text.replace(/[ \t\r\n]+/g, ' ');
                  } else {
                    text = text.replace(/\r\n?/g, '\n');  // Normalize newlines.
                  }
                  // TODO: handle tabs here?
                  chunks[k] = text;
                  spans[k << 1] = length;
                  length += text.length;
                  spans[(k++ << 1) | 1] = node;
                }
              }
            }
          
            walk(node);
          
            return {
              sourceCode: chunks.join('').replace(/\n$/, ''),
              spans: spans
            };
          }
        
          /**
           * Apply the given language handler to sourceCode and add the resulting
           * decorations to out.
           * @param {number} basePos the index of sourceCode within the chunk of source
           *    whose decorations are already present on out.
           */
          function appendDecorations(basePos, sourceCode, langHandler, out) {
            if (!sourceCode) { return; }
            var job = {
              sourceCode: sourceCode,
              basePos: basePos
            };
            langHandler(job);
            out.push.apply(out, job.decorations);
          }
        
          var notWs = /\S/;
        
          /**
           * Given an element, if it contains only one child element and any text nodes
           * it contains contain only space characters, return the sole child element.
           * Otherwise returns undefined.
           * <p>
           * This is meant to return the CODE element in {@code <pre><code ...>} when
           * there is a single child element that contains all the non-space textual
           * content, but not to return anything where there are multiple child elements
           * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
           * is textual content.
           */
          function childContentWrapper(element) {
            var wrapper = undefined;
            for (var c = element.firstChild; c; c = c.nextSibling) {
              var type = c.nodeType;
              wrapper = (type === 1)  // Element Node
                  ? (wrapper ? element : c)
                  : (type === 3)  // Text Node
                  ? (notWs.test(c.nodeValue) ? element : wrapper)
                  : wrapper;
            }
            return wrapper === element ? undefined : wrapper;
          }
        
          /** Given triples of [style, pattern, context] returns a lexing function,
            * The lexing function interprets the patterns to find token boundaries and
            * returns a decoration list of the form
            * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
            * where index_n is an index into the sourceCode, and style_n is a style
            * constant like PR_PLAIN.  index_n-1 <= index_n, and style_n-1 applies to
            * all characters in sourceCode[index_n-1:index_n].
            *
            * The stylePatterns is a list whose elements have the form
            * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
            *
            * Style is a style constant like PR_PLAIN, or can be a string of the
            * form 'lang-FOO', where FOO is a language extension describing the
            * language of the portion of the token in $1 after pattern executes.
            * E.g., if style is 'lang-lisp', and group 1 contains the text
            * '(hello (world))', then that portion of the token will be passed to the
            * registered lisp handler for formatting.
            * The text before and after group 1 will be restyled using this decorator
            * so decorators should take care that this doesn't result in infinite
            * recursion.  For example, the HTML lexer rule for SCRIPT elements looks
            * something like ['lang-js', /<[s]cript>(.+?)<\/script>/].  This may match
            * '<script>foo()<\/script>', which would cause the current decorator to
            * be called with '<script>' which would not match the same rule since
            * group 1 must not be empty, so it would be instead styled as PR_TAG by
            * the generic tag rule.  The handler registered for the 'js' extension would
            * then be called with 'foo()', and finally, the current decorator would
            * be called with '<\/script>' which would not match the original rule and
            * so the generic tag rule would identify it as a tag.
            *
            * Pattern must only match prefixes, and if it matches a prefix, then that
            * match is considered a token with the same style.
            *
            * Context is applied to the last non-whitespace, non-comment token
            * recognized.
            *
            * Shortcut is an optional string of characters, any of which, if the first
            * character, gurantee that this pattern and only this pattern matches.
            *
            * @param {Array} shortcutStylePatterns patterns that always start with
            *   a known character.  Must have a shortcut string.
            * @param {Array} fallthroughStylePatterns patterns that will be tried in
            *   order if the shortcut ones fail.  May have shortcuts.
            *
            * @return {function (Object)} a
            *   function that takes source code and returns a list of decorations.
            */
          function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
            var shortcuts = {};
            var tokenizer;
            (function () {
              var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
              var allRegexs = [];
              var regexKeys = {};
              for (var i = 0, n = allPatterns.length; i < n; ++i) {
                var patternParts = allPatterns[i];
                var shortcutChars = patternParts[3];
                if (shortcutChars) {
                  for (var c = shortcutChars.length; --c >= 0;) {
                    shortcuts[shortcutChars.charAt(c)] = patternParts;
                  }
                }
                var regex = patternParts[1];
                var k = '' + regex;
                if (!regexKeys.hasOwnProperty(k)) {
                  allRegexs.push(regex);
                  regexKeys[k] = null;
                }
              }
              allRegexs.push(/[\0-\uffff]/);
              tokenizer = combinePrefixPatterns(allRegexs);
            })();
        
            var nPatterns = fallthroughStylePatterns.length;
        
            /**
             * Lexes job.sourceCode and produces an output array job.decorations of
             * style classes preceded by the position at which they start in
             * job.sourceCode in order.
             *
             * @param {Object} job an object like <pre>{
             *    sourceCode: {string} sourceText plain text,
             *    basePos: {int} position of job.sourceCode in the larger chunk of
             *        sourceCode.
             * }</pre>
             */
            var decorate = function (job) {
              var sourceCode = job.sourceCode, basePos = job.basePos;
              /** Even entries are positions in source in ascending order.  Odd enties
                * are style markers (e.g., PR_COMMENT) that run from that position until
                * the end.
                * @type {Array.<number|string>}
                */
              var decorations = [basePos, PR_PLAIN];
              var pos = 0;  // index into sourceCode
              var tokens = sourceCode.match(tokenizer) || [];
              var styleCache = {};
        
              for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
                var token = tokens[ti];
                var style = styleCache[token];
                var match = void 0;
        
                var isEmbedded;
                if (typeof style === 'string') {
                  isEmbedded = false;
                } else {
                  var patternParts = shortcuts[token.charAt(0)];
                  if (patternParts) {
                    match = token.match(patternParts[1]);
                    style = patternParts[0];
                  } else {
                    for (var i = 0; i < nPatterns; ++i) {
                      patternParts = fallthroughStylePatterns[i];
                      match = token.match(patternParts[1]);
                      if (match) {
                        style = patternParts[0];
                        break;
                      }
                    }
        
                    if (!match) {  // make sure that we make progress
                      style = PR_PLAIN;
                    }
                  }
        
                  isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
                  if (isEmbedded && !(match && typeof match[1] === 'string')) {
                    isEmbedded = false;
                    style = PR_SOURCE;
                  }
        
                  if (!isEmbedded) { styleCache[token] = style; }
                }
        
                var tokenStart = pos;
                pos += token.length;
        
                if (!isEmbedded) {
                  decorations.push(basePos + tokenStart, style);
                } else {  // Treat group 1 as an embedded block of source code.
                  var embeddedSource = match[1];
                  var embeddedSourceStart = token.indexOf(embeddedSource);
                  var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
                  if (match[2]) {
                    // If embeddedSource can be blank, then it would match at the
                    // beginning which would cause us to infinitely recurse on the
                    // entire token, so we catch the right context in match[2].
                    embeddedSourceEnd = token.length - match[2].length;
                    embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
                  }
                  var lang = style.substring(5);
                  // Decorate the left of the embedded source
                  appendDecorations(
                      basePos + tokenStart,
                      token.substring(0, embeddedSourceStart),
                      decorate, decorations);
                  // Decorate the embedded source
                  appendDecorations(
                      basePos + tokenStart + embeddedSourceStart,
                      embeddedSource,
                      langHandlerForExtension(lang, embeddedSource),
                      decorations);
                  // Decorate the right of the embedded section
                  appendDecorations(
                      basePos + tokenStart + embeddedSourceEnd,
                      token.substring(embeddedSourceEnd),
                      decorate, decorations);
                }
              }
              job.decorations = decorations;
            };
            return decorate;
          }
        
          /** returns a function that produces a list of decorations from source text.
            *
            * This code treats ", ', and ` as string delimiters, and \ as a string
            * escape.  It does not recognize perl's qq() style strings.
            * It has no special handling for double delimiter escapes as in basic, or
            * the tripled delimiters used in python, but should work on those regardless
            * although in those cases a single string literal may be broken up into
            * multiple adjacent string literals.
            *
            * It recognizes C, C++, and shell style comments.
            *
            * @param {Object} options a set of optional parameters.
            * @return {function (Object)} a function that examines the source code
            *     in the input job and builds the decoration list.
            */
          function sourceDecorator(options) {
            var shortcutStylePatterns = [], fallthroughStylePatterns = [];
            if (options['tripleQuotedStrings']) {
              // '''multi-line-string''', 'single-line-string', and double-quoted
              shortcutStylePatterns.push(
                  [PR_STRING,  /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
                   null, '\'"']);
            } else if (options['multiLineStrings']) {
              // 'multi-line-string', "multi-line-string"
              shortcutStylePatterns.push(
                  [PR_STRING,  /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
                   null, '\'"`']);
            } else {
              // 'single-line-string', "single-line-string"
              shortcutStylePatterns.push(
                  [PR_STRING,
                   /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
                   null, '"\'']);
            }
            if (options['verbatimStrings']) {
              // verbatim-string-literal production from the C# grammar.  See issue 93.
              fallthroughStylePatterns.push(
                  [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
            }
            var hc = options['hashComments'];
            if (hc) {
              if (options['cStyleComments']) {
                if (hc > 1) {  // multiline hash comments
                  shortcutStylePatterns.push(
                      [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
                } else {
                  // Stop C preprocessor declarations at an unclosed open comment
                  shortcutStylePatterns.push(
                      [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
                       null, '#']);
                }
                // #include <stdio.h>
                fallthroughStylePatterns.push(
                    [PR_STRING,
                     /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
                     null]);
              } else {
                shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
              }
            }
            if (options['cStyleComments']) {
              fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
              fallthroughStylePatterns.push(
                  [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
            }
            var regexLiterals = options['regexLiterals'];
            if (regexLiterals) {
              /**
               * @const
               */
              var regexExcls = regexLiterals > 1
                ? ''  // Multiline regex literals
                : '\n\r';
              /**
               * @const
               */
              var regexAny = regexExcls ? '.' : '[\\S\\s]';
              /**
               * @const
               */
              var REGEX_LITERAL = (
                  // A regular expression literal starts with a slash that is
                  // not followed by * or / so that it is not confused with
                  // comments.
                  '/(?=[^/*' + regexExcls + '])'
                  // and then contains any number of raw characters,
                  + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
                  // escape sequences (\x5C),
                  +    '|\\x5C' + regexAny
                  // or non-nesting character sets (\x5B\x5D);
                  +    '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
                  +             '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
                  // finally closed by a /.
                  + '/');
              fallthroughStylePatterns.push(
                  ['lang-regex',
                   RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
                   ]);
            }
        
            var types = options['types'];
            if (types) {
              fallthroughStylePatterns.push([PR_TYPE, types]);
            }
        
            var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
            if (keywords.length) {
              fallthroughStylePatterns.push(
                  [PR_KEYWORD,
                   new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
                   null]);
            }
        
            shortcutStylePatterns.push([PR_PLAIN,       /^\s+/, null, ' \r\n\t\xA0']);
        
            var punctuation =
              // The Bash man page says
        
              // A word is a sequence of characters considered as a single
              // unit by GRUB. Words are separated by metacharacters,
              // which are the following plus space, tab, and newline: { }
              // | & $ ; < >
              // ...
              
              // A word beginning with # causes that word and all remaining
              // characters on that line to be ignored.
        
              // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
              // comment but empirically
              // $ echo {#}
              // {#}
              // $ echo \$#
              // $#
              // $ echo }#
              // }#
        
              // so /(?:^|[|&;<>\s])/ is more appropriate.
        
              // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
              // suggests that this definition is compatible with a
              // default mode that tries to use a single token definition
              // to recognize both bash/python style comments and C
              // preprocessor directives.
        
              // This definition of punctuation does not include # in the list of
              // follow-on exclusions, so # will not be broken before if preceeded
              // by a punctuation character.  We could try to exclude # after
              // [|&;<>] but that doesn't seem to cause many major problems.
              // If that does turn out to be a problem, we should change the below
              // when hc is truthy to include # in the run of punctuation characters
              // only when not followint [|&;<>].
              '^.[^\\s\\w.$@\'"`/\\\\]*';
            if (options['regexLiterals']) {
              punctuation += '(?!\s*\/)';
            }
        
            fallthroughStylePatterns.push(
                // TODO(mikesamuel): recognize non-latin letters and numerals in idents
                [PR_LITERAL,     /^@[a-z_$][a-z_$@0-9]*/i, null],
                [PR_TYPE,        /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
                [PR_PLAIN,       /^[a-z_$][a-z_$@0-9]*/i, null],
                [PR_LITERAL,
                 new RegExp(
                     '^(?:'
                     // A hex number
                     + '0x[a-f0-9]+'
                     // or an octal or decimal number,
                     + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
                     // possibly in scientific notation
                     + '(?:e[+\\-]?\\d+)?'
                     + ')'
                     // with an optional modifier like UL for unsigned long
                     + '[a-z]*', 'i'),
                 null, '0123456789'],
                // Don't treat escaped quotes in bash as starting strings.
                // See issue 144.
                [PR_PLAIN,       /^\\[\s\S]?/, null],
                [PR_PUNCTUATION, new RegExp(punctuation), null]);
        
            return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
          }
        
          var decorateSource = sourceDecorator({
                'keywords': ALL_KEYWORDS,
                'hashComments': true,
                'cStyleComments': true,
                'multiLineStrings': true,
                'regexLiterals': true
              });
        
          /**
           * Given a DOM subtree, wraps it in a list, and puts each line into its own
           * list item.
           *
           * @param {Node} node modified in place.  Its content is pulled into an
           *     HTMLOListElement, and each line is moved into a separate list item.
           *     This requires cloning elements, so the input might not have unique
           *     IDs after numbering.
           * @param {boolean} isPreformatted true iff white-space in text nodes should
           *     be treated as significant.
           */
          function numberLines(node, opt_startLineNum, isPreformatted) {
            var nocode = /(?:^|\s)nocode(?:\s|$)/;
            var lineBreak = /\r\n?|\n/;
          
            var document = node.ownerDocument;
          
            var li = document.createElement('li');
            while (node.firstChild) {
              li.appendChild(node.firstChild);
            }
            // An array of lines.  We split below, so this is initialized to one
            // un-split line.
            var listItems = [li];
          
            function walk(node) {
              var type = node.nodeType;
              if (type == 1 && !nocode.test(node.className)) {  // Element
                if ('br' === node.nodeName) {
                  breakAfter(node);
                  // Discard the <BR> since it is now flush against a </LI>.
                  if (node.parentNode) {
                    node.parentNode.removeChild(node);
                  }
                } else {
                  for (var child = node.firstChild; child; child = child.nextSibling) {
                    walk(child);
                  }
                }
              } else if ((type == 3 || type == 4) && isPreformatted) {  // Text
                var text = node.nodeValue;
                var match = text.match(lineBreak);
                if (match) {
                  var firstLine = text.substring(0, match.index);
                  node.nodeValue = firstLine;
                  var tail = text.substring(match.index + match[0].length);
                  if (tail) {
                    var parent = node.parentNode;
                    parent.insertBefore(
                      document.createTextNode(tail), node.nextSibling);
                  }
                  breakAfter(node);
                  if (!firstLine) {
                    // Don't leave blank text nodes in the DOM.
                    node.parentNode.removeChild(node);
                  }
                }
              }
            }
          
            // Split a line after the given node.
            function breakAfter(lineEndNode) {
              // If there's nothing to the right, then we can skip ending the line
              // here, and move root-wards since splitting just before an end-tag
              // would require us to create a bunch of empty copies.
              while (!lineEndNode.nextSibling) {
                lineEndNode = lineEndNode.parentNode;
                if (!lineEndNode) { return; }
              }
          
              function breakLeftOf(limit, copy) {
                // Clone shallowly if this node needs to be on both sides of the break.
                var rightSide = copy ? limit.cloneNode(false) : limit;
                var parent = limit.parentNode;
                if (parent) {
                  // We clone the parent chain.
                  // This helps us resurrect important styling elements that cross lines.
                  // E.g. in <i>Foo<br>Bar</i>
                  // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
                  var parentClone = breakLeftOf(parent, 1);
                  // Move the clone and everything to the right of the original
                  // onto the cloned parent.
                  var next = limit.nextSibling;
                  parentClone.appendChild(rightSide);
                  for (var sibling = next; sibling; sibling = next) {
                    next = sibling.nextSibling;
                    parentClone.appendChild(sibling);
                  }
                }
                return rightSide;
              }
          
              var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
          
              // Walk the parent chain until we reach an unattached LI.
              for (var parent;
                   // Check nodeType since IE invents document fragments.
                   (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
                copiedListItem = parent;
              }
              // Put it on the list of lines for later processing.
              listItems.push(copiedListItem);
            }
          
            // Split lines while there are lines left to split.
            for (var i = 0;  // Number of lines that have been split so far.
                 i < listItems.length;  // length updated by breakAfter calls.
                 ++i) {
              walk(listItems[i]);
            }
          
            // Make sure numeric indices show correctly.
            if (opt_startLineNum === (opt_startLineNum|0)) {
              listItems[0].setAttribute('value', opt_startLineNum);
            }
          
            var ol = document.createElement('ol');
            ol.className = 'linenums';
            var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
            for (var i = 0, n = listItems.length; i < n; ++i) {
              li = listItems[i];
              // Stick a class on the LIs so that stylesheets can
              // color odd/even rows, or any other row pattern that
              // is co-prime with 10.
              li.className = 'L' + ((i + offset) % 10);
              if (!li.firstChild) {
                li.appendChild(document.createTextNode('\xA0'));
              }
              ol.appendChild(li);
            }
          
            node.appendChild(ol);
          }    
          /**
           * Breaks {@code job.sourceCode} around style boundaries in
           * {@code job.decorations} and modifies {@code job.sourceNode} in place.
           * @param {Object} job like <pre>{
           *    sourceCode: {string} source as plain text,
           *    sourceNode: {HTMLElement} the element containing the source,
           *    spans: {Array.<number|Node>} alternating span start indices into source
           *       and the text node or element (e.g. {@code <BR>}) corresponding to that
           *       span.
           *    decorations: {Array.<number|string} an array of style classes preceded
           *       by the position at which they start in job.sourceCode in order
           * }</pre>
           * @private
           */
          function recombineTagsAndDecorations(job) {
            var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
            isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
            var newlineRe = /\n/g;
          
            var source = job.sourceCode;
            var sourceLength = source.length;
            // Index into source after the last code-unit recombined.
            var sourceIndex = 0;
          
            var spans = job.spans;
            var nSpans = spans.length;
            // Index into spans after the last span which ends at or before sourceIndex.
            var spanIndex = 0;
          
            var decorations = job.decorations;
            var nDecorations = decorations.length;
            // Index into decorations after the last decoration which ends at or before
            // sourceIndex.
            var decorationIndex = 0;
          
            // Remove all zero-length decorations.
            decorations[nDecorations] = sourceLength;
            var decPos, i;
            for (i = decPos = 0; i < nDecorations;) {
              if (decorations[i] !== decorations[i + 2]) {
                decorations[decPos++] = decorations[i++];
                decorations[decPos++] = decorations[i++];
              } else {
                i += 2;
              }
            }
            nDecorations = decPos;
          
            // Simplify decorations.
            for (i = decPos = 0; i < nDecorations;) {
              var startPos = decorations[i];
              // Conflate all adjacent decorations that use the same style.
              var startDec = decorations[i + 1];
              var end = i + 2;
              while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
                end += 2;
              }
              decorations[decPos++] = startPos;
              decorations[decPos++] = startDec;
              i = end;
            }
          
            nDecorations = decorations.length = decPos;
          
            var sourceNode = job.sourceNode;
            var oldDisplay;
            if (sourceNode) {
              oldDisplay = sourceNode.style.display;
              sourceNode.style.display = 'none';
            }
            try {
              var decoration = null;
              while (spanIndex < nSpans) {
                var spanStart = spans[spanIndex];
                var spanEnd = spans[spanIndex + 2] || sourceLength;
          
                var decEnd = decorations[decorationIndex + 2] || sourceLength;
          
                var end = Math.min(spanEnd, decEnd);
          
                var textNode = spans[spanIndex + 1];
                var styledText;
                if (textNode.nodeType !== 1  // Don't muck with <BR>s or <LI>s
                    // Don't introduce spans around empty text nodes.
                    && (styledText = source.substring(sourceIndex, end))) {
                  // This may seem bizarre, and it is.  Emitting LF on IE causes the
                  // code to display with spaces instead of line breaks.
                  // Emitting Windows standard issue linebreaks (CRLF) causes a blank
                  // space to appear at the beginning of every line but the first.
                  // Emitting an old Mac OS 9 line separator makes everything spiffy.
                  if (isIE8OrEarlier) {
                    styledText = styledText.replace(newlineRe, '\r');
                  }
                  textNode.nodeValue = styledText;
                  var document = textNode.ownerDocument;
                  var span = document.createElement('span');
                  span.className = decorations[decorationIndex + 1];
                  var parentNode = textNode.parentNode;
                  parentNode.replaceChild(span, textNode);
                  span.appendChild(textNode);
                  if (sourceIndex < spanEnd) {  // Split off a text node.
                    spans[spanIndex + 1] = textNode
                        // TODO: Possibly optimize by using '' if there's no flicker.
                        = document.createTextNode(source.substring(end, spanEnd));
                    parentNode.insertBefore(textNode, span.nextSibling);
                  }
                }
          
                sourceIndex = end;
          
                if (sourceIndex >= spanEnd) {
                  spanIndex += 2;
                }
                if (sourceIndex >= decEnd) {
                  decorationIndex += 2;
                }
              }
            } finally {
              if (sourceNode) {
                sourceNode.style.display = oldDisplay;
              }
            }
          }
        
          /** Maps language-specific file extensions to handlers. */
          var langHandlerRegistry = {};
          /** Register a language handler for the given file extensions.
            * @param {function (Object)} handler a function from source code to a list
            *      of decorations.  Takes a single argument job which describes the
            *      state of the computation.   The single parameter has the form
            *      {@code {
            *        sourceCode: {string} as plain text.
            *        decorations: {Array.<number|string>} an array of style classes
            *                     preceded by the position at which they start in
            *                     job.sourceCode in order.
            *                     The language handler should assigned this field.
            *        basePos: {int} the position of source in the larger source chunk.
            *                 All positions in the output decorations array are relative
            *                 to the larger source chunk.
            *      } }
            * @param {Array.<string>} fileExtensions
            */
          function registerLangHandler(handler, fileExtensions) {
            for (var i = fileExtensions.length; --i >= 0;) {
              var ext = fileExtensions[i];
              if (!langHandlerRegistry.hasOwnProperty(ext)) {
                langHandlerRegistry[ext] = handler;
              } else if (win['console']) {
                console['warn']('cannot override language handler %s', ext);
              }
            }
          }
          function langHandlerForExtension(extension, source) {
            if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
              // Treat it as markup if the first non whitespace character is a < and
              // the last non-whitespace character is a >.
              extension = /^\s*</.test(source)
                  ? 'default-markup'
                  : 'default-code';
            }
            return langHandlerRegistry[extension];
          }
          registerLangHandler(decorateSource, ['default-code']);
          registerLangHandler(
              createSimpleLexer(
                  [],
                  [
                   [PR_PLAIN,       /^[^<?]+/],
                   [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
                   [PR_COMMENT,     /^<\!--[\s\S]*?(?:-\->|$)/],
                   // Unescaped content in an unknown language
                   ['lang-',        /^<\?([\s\S]+?)(?:\?>|$)/],
                   ['lang-',        /^<%([\s\S]+?)(?:%>|$)/],
                   [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
                   ['lang-',        /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
                   // Unescaped content in javascript.  (Or possibly vbscript).
                   ['lang-js',      /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
                   // Contains unescaped stylesheet content
                   ['lang-css',     /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
                   ['lang-in.tag',  /^(<\/?[a-z][^<>]*>)/i]
                  ]),
              ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
          registerLangHandler(
              createSimpleLexer(
                  [
                   [PR_PLAIN,        /^[\s]+/, null, ' \t\r\n'],
                   [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
                   ],
                  [
                   [PR_TAG,          /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
                   [PR_ATTRIB_NAME,  /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
                   ['lang-uq.val',   /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
                   [PR_PUNCTUATION,  /^[=<>\/]+/],
                   ['lang-js',       /^on\w+\s*=\s*\"([^\"]+)\"/i],
                   ['lang-js',       /^on\w+\s*=\s*\'([^\']+)\'/i],
                   ['lang-js',       /^on\w+\s*=\s*([^\"\'>\s]+)/i],
                   ['lang-css',      /^style\s*=\s*\"([^\"]+)\"/i],
                   ['lang-css',      /^style\s*=\s*\'([^\']+)\'/i],
                   ['lang-css',      /^style\s*=\s*([^\"\'>\s]+)/i]
                   ]),
              ['in.tag']);
          registerLangHandler(
              createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
          registerLangHandler(sourceDecorator({
                  'keywords': CPP_KEYWORDS,
                  'hashComments': true,
                  'cStyleComments': true,
                  'types': C_TYPES
                }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
          registerLangHandler(sourceDecorator({
                  'keywords': 'null,true,false'
                }), ['json']);
          registerLangHandler(sourceDecorator({
                  'keywords': CSHARP_KEYWORDS,
                  'hashComments': true,
                  'cStyleComments': true,
                  'verbatimStrings': true,
                  'types': C_TYPES
                }), ['cs']);
          registerLangHandler(sourceDecorator({
                  'keywords': JAVA_KEYWORDS,
                  'cStyleComments': true
                }), ['java']);
          registerLangHandler(sourceDecorator({
                  'keywords': SH_KEYWORDS,
                  'hashComments': true,
                  'multiLineStrings': true
                }), ['bash', 'bsh', 'csh', 'sh']);
          registerLangHandler(sourceDecorator({
                  'keywords': PYTHON_KEYWORDS,
                  'hashComments': true,
                  'multiLineStrings': true,
                  'tripleQuotedStrings': true
                }), ['cv', 'py', 'python']);
          registerLangHandler(sourceDecorator({
                  'keywords': PERL_KEYWORDS,
                  'hashComments': true,
                  'multiLineStrings': true,
                  'regexLiterals': 2  // multiline regex literals
                }), ['perl', 'pl', 'pm']);
          registerLangHandler(sourceDecorator({
                  'keywords': RUBY_KEYWORDS,
                  'hashComments': true,
                  'multiLineStrings': true,
                  'regexLiterals': true
                }), ['rb', 'ruby']);
          registerLangHandler(sourceDecorator({
                  'keywords': JSCRIPT_KEYWORDS,
                  'cStyleComments': true,
                  'regexLiterals': true
                }), ['javascript', 'js']);
          registerLangHandler(sourceDecorator({
                  'keywords': COFFEE_KEYWORDS,
                  'hashComments': 3,  // ### style block comments
                  'cStyleComments': true,
                  'multilineStrings': true,
                  'tripleQuotedStrings': true,
                  'regexLiterals': true
                }), ['coffee']);
          registerLangHandler(sourceDecorator({
                  'keywords': RUST_KEYWORDS,
                  'cStyleComments': true,
                  'multilineStrings': true
                }), ['rc', 'rs', 'rust']);
          registerLangHandler(
              createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
        
          function applyDecorator(job) {
            var opt_langExtension = job.langExtension;
        
            try {
              // Extract tags, and convert the source code to plain text.
              var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
              /** Plain text. @type {string} */
              var source = sourceAndSpans.sourceCode;
              job.sourceCode = source;
              job.spans = sourceAndSpans.spans;
              job.basePos = 0;
        
              // Apply the appropriate language handler
              langHandlerForExtension(opt_langExtension, source)(job);
        
              // Integrate the decorations and tags back into the source code,
              // modifying the sourceNode in place.
              recombineTagsAndDecorations(job);
            } catch (e) {
              if (win['console']) {
                console['log'](e && e['stack'] || e);
              }
            }
          }
        
          /**
           * Pretty print a chunk of code.
           * @param sourceCodeHtml {string} The HTML to pretty print.
           * @param opt_langExtension {string} The language name to use.
           *     Typically, a filename extension like 'cpp' or 'java'.
           * @param opt_numberLines {number|boolean} True to number lines,
           *     or the 1-indexed number of the first line in sourceCodeHtml.
           */
          function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
            var container = document.createElement('div');
            // This could cause images to load and onload listeners to fire.
            // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
            // We assume that the inner HTML is from a trusted source.
            // The pre-tag is required for IE8 which strips newlines from innerHTML
            // when it is injected into a <pre> tag.
            // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
            // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
            container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
            container = container.firstChild;
            if (opt_numberLines) {
              numberLines(container, opt_numberLines, true);
            }
        
            var job = {
              langExtension: opt_langExtension,
              numberLines: opt_numberLines,
              sourceNode: container,
              pre: 1
            };
            applyDecorator(job);
            return container.innerHTML;
          }
        
           /**
            * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
            * {@code class=prettyprint} and prettify them.
            *
            * @param {Function} opt_whenDone called when prettifying is done.
            * @param {HTMLElement|HTMLDocument} opt_root an element or document
            *   containing all the elements to pretty print.
            *   Defaults to {@code document.body}.
            */
          function $prettyPrint(opt_whenDone, opt_root) {
            var root = opt_root || document.body;
            var doc = root.ownerDocument || document;
            function byTagName(tn) { return root.getElementsByTagName(tn); }
            // fetch a list of nodes to rewrite
            var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
            var elements = [];
            for (var i = 0; i < codeSegments.length; ++i) {
              for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
                elements.push(codeSegments[i][j]);
              }
            }
            codeSegments = null;
        
            var clock = Date;
            if (!clock['now']) {
              clock = { 'now': function () { return +(new Date); } };
            }
        
            // The loop is broken into a series of continuations to make sure that we
            // don't make the browser unresponsive when rewriting a large page.
            var k = 0;
            var prettyPrintingJob;
        
            var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
            var prettyPrintRe = /\bprettyprint\b/;
            var prettyPrintedRe = /\bprettyprinted\b/;
            var preformattedTagNameRe = /pre|xmp/i;
            var codeRe = /^code$/i;
            var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
            var EMPTY = {};
        
            function doWork() {
              var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
                             clock['now']() + 250 /* ms */ :
                             Infinity);
              for (; k < elements.length && clock['now']() < endTime; k++) {
                var cs = elements[k];
        
                // Look for a preceding comment like
                // <?prettify lang="..." linenums="..."?>
                var attrs = EMPTY;
                {
                  for (var preceder = cs; (preceder = preceder.previousSibling);) {
                    var nt = preceder.nodeType;
                    // <?foo?> is parsed by HTML 5 to a comment node (8)
                    // like <!--?foo?-->, but in XML is a processing instruction
                    var value = (nt === 7 || nt === 8) && preceder.nodeValue;
                    if (value
                        ? !/^\??prettify\b/.test(value)
                        : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
                      // Skip over white-space text nodes but not others.
                      break;
                    }
                    if (value) {
                      attrs = {};
                      value.replace(
                          /\b(\w+)=([\w:.%+-]+)/g,
                        function (_, name, value) { attrs[name] = value; });
                      break;
                    }
                  }
                }
        
                var className = cs.className;
                if ((attrs !== EMPTY || prettyPrintRe.test(className))
                    // Don't redo this if we've already done it.
                    // This allows recalling pretty print to just prettyprint elements
                    // that have been added to the page since last call.
                    && !prettyPrintedRe.test(className)) {
        
                  // make sure this is not nested in an already prettified element
                  var nested = false;
                  for (var p = cs.parentNode; p; p = p.parentNode) {
                    var tn = p.tagName;
                    if (preCodeXmpRe.test(tn)
                        && p.className && prettyPrintRe.test(p.className)) {
                      nested = true;
                      break;
                    }
                  }
                  if (!nested) {
                    // Mark done.  If we fail to prettyprint for whatever reason,
                    // we shouldn't try again.
                    cs.className += ' prettyprinted';
        
                    // If the classes includes a language extensions, use it.
                    // Language extensions can be specified like
                    //     <pre class="prettyprint lang-cpp">
                    // the language extension "cpp" is used to find a language handler
                    // as passed to PR.registerLangHandler.
                    // HTML5 recommends that a language be specified using "language-"
                    // as the prefix instead.  Google Code Prettify supports both.
                    // http://dev.w3.org/html5/spec-author-view/the-code-element.html
                    var langExtension = attrs['lang'];
                    if (!langExtension) {
                      langExtension = className.match(langExtensionRe);
                      // Support <pre class="prettyprint"><code class="language-c">
                      var wrapper;
                      if (!langExtension && (wrapper = childContentWrapper(cs))
                          && codeRe.test(wrapper.tagName)) {
                        langExtension = wrapper.className.match(langExtensionRe);
                      }
        
                      if (langExtension) { langExtension = langExtension[1]; }
                    }
        
                    var preformatted;
                    if (preformattedTagNameRe.test(cs.tagName)) {
                      preformatted = 1;
                    } else {
                      var currentStyle = cs['currentStyle'];
                      var defaultView = doc.defaultView;
                      var whitespace = (
                          currentStyle
                          ? currentStyle['whiteSpace']
                          : (defaultView
                             && defaultView.getComputedStyle)
                          ? defaultView.getComputedStyle(cs, null)
                          .getPropertyValue('white-space')
                          : 0);
                      preformatted = whitespace
                          && 'pre' === whitespace.substring(0, 3);
                    }
        
                    // Look for a class like linenums or linenums:<n> where <n> is the
                    // 1-indexed number of the first line.
                    var lineNums = attrs['linenums'];
                    if (!(lineNums = lineNums === 'true' || +lineNums)) {
                      lineNums = className.match(/\blinenums\b(?::(\d+))?/);
                      lineNums =
                        lineNums
                        ? lineNums[1] && lineNums[1].length
                          ? +lineNums[1] : true
                        : false;
                    }
                    if (lineNums) { numberLines(cs, lineNums, preformatted); }
        
                    // do the pretty printing
                    prettyPrintingJob = {
                      langExtension: langExtension,
                      sourceNode: cs,
                      numberLines: lineNums,
                      pre: preformatted
                    };
                    applyDecorator(prettyPrintingJob);
                  }
                }
              }
              if (k < elements.length) {
                // finish up in a continuation
                setTimeout(doWork, 250);
              } else if ('function' === typeof opt_whenDone) {
                opt_whenDone();
              }
            }
        
            doWork();
          }
        
          /**
           * Contains functions for creating and registering new language handlers.
           * @type {Object}
           */
          var PR = win['PR'] = {
                'createSimpleLexer': createSimpleLexer,
                'registerLangHandler': registerLangHandler,
                'sourceDecorator': sourceDecorator,
                'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
                'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
                'PR_COMMENT': PR_COMMENT,
                'PR_DECLARATION': PR_DECLARATION,
                'PR_KEYWORD': PR_KEYWORD,
                'PR_LITERAL': PR_LITERAL,
                'PR_NOCODE': PR_NOCODE,
                'PR_PLAIN': PR_PLAIN,
                'PR_PUNCTUATION': PR_PUNCTUATION,
                'PR_SOURCE': PR_SOURCE,
                'PR_STRING': PR_STRING,
                'PR_TAG': PR_TAG,
                'PR_TYPE': PR_TYPE,
                'prettyPrintOne':
                   IN_GLOBAL_SCOPE
                     ? (win['prettyPrintOne'] = $prettyPrintOne)
                     : (prettyPrintOne = $prettyPrintOne),
                'prettyPrint': prettyPrint =
                   IN_GLOBAL_SCOPE
                     ? (win['prettyPrint'] = $prettyPrint)
                     : (prettyPrint = $prettyPrint)
              };
        
          // Make PR available via the Asynchronous Module Definition (AMD) API.
          // Per https://github.com/amdjs/amdjs-api/wiki/AMD:
          // The Asynchronous Module Definition (AMD) API specifies a
          // mechanism for defining modules such that the module and its
          // dependencies can be asynchronously loaded.
          // ...
          // To allow a clear indicator that a global define function (as
          // needed for script src browser loading) conforms to the AMD API,
          // any global define function SHOULD have a property called "amd"
          // whose value is an object. This helps avoid conflict with any
          // other existing JavaScript code that could have defined a define()
          // function that does not conform to the AMD API.
          if (typeof define === "function" && define['amd']) {
            define("google-code-prettify", [], function () {
              return PR; 
            });
          }
        })();
        return prettyPrint;
      })();
    
      // If this script is deferred or async and the document is already
      // loaded we need to wait for language handlers to load before performing
      // any autorun.
      function onLangsLoaded() {
        if (autorun) {
          contentLoaded(
            function () {
              var n = callbacks.length;
              var callback = n ? function () {
                for (var i = 0; i < n; ++i) {
                  (function (i) {
                     setTimeout(
                       function () {
                         win['exports'][callbacks[i]].apply(win, arguments);
                       }, 0);
                   })(i);
                }
              } : void 0;
              prettyPrint(callback);
            });
        }
      }
      checkPendingLanguages();
    
    }());
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/prettify.css����������������������������������������������������������������0000640�0001750�0001750�00000003042�12115200050�015540� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Pretty printing styles. Used with prettify.js. */
    
    /* SPAN elements with the classes below are added by prettyprint. */
    .pln { color: #000 }  /* plain text */
    
    @media screen {
      .str { color: #080 }  /* string content */
      .kwd { color: #008 }  /* a keyword */
      .com { color: #800 }  /* a comment */
      .typ { color: #606 }  /* a type name */
      .lit { color: #066 }  /* a literal value */
      /* punctuation, lisp open bracket, lisp close bracket */
      .pun, .opn, .clo { color: #660 }
      .tag { color: #008 }  /* a markup tag name */
      .atn { color: #606 }  /* a markup attribute name */
      .atv { color: #080 }  /* a markup attribute value */
      .dec, .var { color: #606 }  /* a declaration; a variable name */
      .fun { color: red }  /* a function name */
    }
    
    /* Use higher contrast and text-weight for printable form. */
    @media print, projection {
      .str { color: #060 }
      .kwd { color: #006; font-weight: bold }
      .com { color: #600; font-style: italic }
      .typ { color: #404; font-weight: bold }
      .lit { color: #044 }
      .pun, .opn, .clo { color: #440 }
      .tag { color: #006; font-weight: bold }
      .atn { color: #404 }
      .atv { color: #060 }
    }
    
    /* Put a border around prettyprinted code snippets. */
    pre.prettyprint { padding: 2px; border: 1px solid #888 }
    
    /* Specify class=linenums on a pre to get line numbering */
    ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
    li.L0,
    li.L1,
    li.L2,
    li.L3,
    li.L5,
    li.L6,
    li.L7,
    li.L8 { list-style-type: none }
    /* Alternate shading for lines */
    li.L1,
    li.L3,
    li.L5,
    li.L7,
    li.L9 { background: #eee }
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/prettify.js�����������������������������������������������������������������0000440�0001750�0001750�00000173530�12115200050�015374� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2006 Google Inc.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    /**
     * @fileoverview
     * some functions for browser-side pretty printing of code contained in html.
     *
     * <p>
     * For a fairly comprehensive set of languages see the
     * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
     * file that came with this source.  At a minimum, 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 subset of Perl, but, because of commenting conventions, doesn't work on
     * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
     * <p>
     * Usage: <ol>
     * <li> include this source file in an html page via
     *   {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
     * <li> define style rules.  See the example page for examples.
     * <li> mark the {@code <pre>} and {@code <code>} tags in your source with
     *    {@code class=prettyprint.}
     *    You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
     *    printer needs to do more substantial DOM manipulations to support that, so
     *    some css styles may not be preserved.
     * </ol>
     * That's it.  I wanted to keep the API as simple as possible, so there's no
     * need to specify which language the code is in, but if you wish, you can add
     * another class to the {@code <pre>} or {@code <code>} element to specify the
     * language, as in {@code <pre class="prettyprint lang-java">}.  Any class that
     * starts with "lang-" followed by a file extension, specifies the file type.
     * See the "lang-*.js" files in this directory for code that implements
     * per-language file handlers.
     * <p>
     * Change log:<br>
     * cbeust, 2006/08/22
     * <blockquote>
     *   Java annotations (start with "@") are now captured as literals ("lit")
     * </blockquote>
     * @requires console
     */
    
    // JSLint declarations
    /*global console, document, navigator, setTimeout, window, define */
    
    /** @define {boolean} */
    var IN_GLOBAL_SCOPE = true;
    
    /**
     * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
     * UI events.
     * If set to {@code false}, {@code prettyPrint()} is synchronous.
     */
    window['PR_SHOULD_USE_CONTINUATION'] = true;
    
    /**
     * Pretty print a chunk of code.
     * @param {string} sourceCodeHtml The HTML to pretty print.
     * @param {string} opt_langExtension The language name to use.
     *     Typically, a filename extension like 'cpp' or 'java'.
     * @param {number|boolean} opt_numberLines True to number lines,
     *     or the 1-indexed number of the first line in sourceCodeHtml.
     * @return {string} code as html, but prettier
     */
    var prettyPrintOne;
    /**
     * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
     * {@code class=prettyprint} and prettify them.
     *
     * @param {Function} opt_whenDone called when prettifying is done.
     * @param {HTMLElement|HTMLDocument} opt_root an element or document
     *   containing all the elements to pretty print.
     *   Defaults to {@code document.body}.
     */
    var prettyPrint;
    
    
    (function () {
      var win = window;
      // Keyword lists for various languages.
      // We use things that coerce to strings to make them compact when minified
      // and to defeat aggressive optimizers that fold large string constants.
      var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
      var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," + 
          "double,enum,extern,float,goto,inline,int,long,register,short,signed," +
          "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
      var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
          "new,operator,private,protected,public,this,throw,true,try,typeof"];
      var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
          "concept,concept_map,const_cast,constexpr,decltype,delegate," +
          "dynamic_cast,explicit,export,friend,generic,late_check," +
          "mutable,namespace,nullptr,property,reinterpret_cast,static_assert," +
          "static_cast,template,typeid,typename,using,virtual,where"];
      var JAVA_KEYWORDS = [COMMON_KEYWORDS,
          "abstract,assert,boolean,byte,extends,final,finally,implements,import," +
          "instanceof,interface,null,native,package,strictfp,super,synchronized," +
          "throws,transient"];
      var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
          "as,base,by,checked,decimal,delegate,descending,dynamic,event," +
          "fixed,foreach,from,group,implicit,in,internal,into,is,let," +
          "lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
          "sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
          "var,virtual,where"];
      var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
          "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
          "throw,true,try,unless,until,when,while,yes";
      var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
          "debugger,eval,export,function,get,null,set,undefined,var,with," +
          "Infinity,NaN"];
      var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
          "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
          "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
      var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
          "elif,except,exec,finally,from,global,import,in,is,lambda," +
          "nonlocal,not,or,pass,print,raise,try,with,yield," +
          "False,True,None"];
      var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
          "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
          "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
          "BEGIN,END"];
       var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," +
          "enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," +
          "pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"];
      var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
          "function,in,local,set,then,until"];
      var ALL_KEYWORDS = [
          CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
          PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
      var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
    
      // token style names.  correspond to css classes
      /**
       * token style for a string literal
       * @const
       */
      var PR_STRING = 'str';
      /**
       * token style for a keyword
       * @const
       */
      var PR_KEYWORD = 'kwd';
      /**
       * token style for a comment
       * @const
       */
      var PR_COMMENT = 'com';
      /**
       * token style for a type
       * @const
       */
      var PR_TYPE = 'typ';
      /**
       * token style for a literal value.  e.g. 1, null, true.
       * @const
       */
      var PR_LITERAL = 'lit';
      /**
       * token style for a punctuation string.
       * @const
       */
      var PR_PUNCTUATION = 'pun';
      /**
       * token style for plain text.
       * @const
       */
      var PR_PLAIN = 'pln';
    
      /**
       * token style for an sgml tag.
       * @const
       */
      var PR_TAG = 'tag';
      /**
       * token style for a markup declaration such as a DOCTYPE.
       * @const
       */
      var PR_DECLARATION = 'dec';
      /**
       * token style for embedded source.
       * @const
       */
      var PR_SOURCE = 'src';
      /**
       * token style for an sgml attribute name.
       * @const
       */
      var PR_ATTRIB_NAME = 'atn';
      /**
       * token style for an sgml attribute value.
       * @const
       */
      var PR_ATTRIB_VALUE = 'atv';
    
      /**
       * A class that indicates a section of markup that is not code, e.g. to allow
       * embedding of line numbers within code listings.
       * @const
       */
      var PR_NOCODE = 'nocode';
    
      
      
      /**
       * A set of tokens that can precede a regular expression literal in
       * javascript
       * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
       * has the full list, but I've removed ones that might be problematic when
       * seen in languages that don't support regular expression literals.
       *
       * <p>Specifically, I've removed any keywords that can't precede a regexp
       * literal in a syntactically legal javascript program, and I've removed the
       * "in" keyword since it's not a keyword in many languages, and might be used
       * as a count of inches.
       *
       * <p>The link above does not accurately describe EcmaScript rules since
       * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
       * very well in practice.
       *
       * @private
       * @const
       */
      var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
      
      // CAVEAT: this does not properly handle the case where a regular
      // expression immediately follows another since a regular expression may
      // have flags for case-sensitivity and the like.  Having regexp tokens
      // adjacent is not valid in any language I'm aware of, so I'm punting.
      // TODO: maybe style special characters inside a regexp as punctuation.
    
      /**
       * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
       * matches the union of the sets of strings matched by the input RegExp.
       * Since it matches globally, if the input strings have a start-of-input
       * anchor (/^.../), it is ignored for the purposes of unioning.
       * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
       * @return {RegExp} a global regex.
       */
      function combinePrefixPatterns(regexs) {
        var capturedGroupIndex = 0;
      
        var needToFoldCase = false;
        var ignoreCase = false;
        for (var i = 0, n = regexs.length; i < n; ++i) {
          var regex = regexs[i];
          if (regex.ignoreCase) {
            ignoreCase = true;
          } else if (/[a-z]/i.test(regex.source.replace(
                         /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
            needToFoldCase = true;
            ignoreCase = false;
            break;
          }
        }
      
        var escapeCharToCodeUnit = {
          'b': 8,
          't': 9,
          'n': 0xa,
          'v': 0xb,
          'f': 0xc,
          'r': 0xd
        };
      
        function decodeEscape(charsetPart) {
          var cc0 = charsetPart.charCodeAt(0);
          if (cc0 !== 92 /* \\ */) {
            return cc0;
          }
          var c1 = charsetPart.charAt(1);
          cc0 = escapeCharToCodeUnit[c1];
          if (cc0) {
            return cc0;
          } else if ('0' <= c1 && c1 <= '7') {
            return parseInt(charsetPart.substring(1), 8);
          } else if (c1 === 'u' || c1 === 'x') {
            return parseInt(charsetPart.substring(2), 16);
          } else {
            return charsetPart.charCodeAt(1);
          }
        }
      
        function encodeEscape(charCode) {
          if (charCode < 0x20) {
            return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
          }
          var ch = String.fromCharCode(charCode);
          return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
              ? "\\" + ch : ch;
        }
      
        function caseFoldCharset(charSet) {
          var charsetParts = charSet.substring(1, charSet.length - 1).match(
              new RegExp(
                  '\\\\u[0-9A-Fa-f]{4}'
                  + '|\\\\x[0-9A-Fa-f]{2}'
                  + '|\\\\[0-3][0-7]{0,2}'
                  + '|\\\\[0-7]{1,2}'
                  + '|\\\\[\\s\\S]'
                  + '|-'
                  + '|[^-\\\\]',
                  'g'));
          var ranges = [];
          var inverse = charsetParts[0] === '^';
      
          var out = ['['];
          if (inverse) { out.push('^'); }
      
          for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
            var p = charsetParts[i];
            if (/\\[bdsw]/i.test(p)) {  // Don't muck with named groups.
              out.push(p);
            } else {
              var start = decodeEscape(p);
              var end;
              if (i + 2 < n && '-' === charsetParts[i + 1]) {
                end = decodeEscape(charsetParts[i + 2]);
                i += 2;
              } else {
                end = start;
              }
              ranges.push([start, end]);
              // If the range might intersect letters, then expand it.
              // This case handling is too simplistic.
              // It does not deal with non-latin case folding.
              // It works for latin source code identifiers though.
              if (!(end < 65 || start > 122)) {
                if (!(end < 65 || start > 90)) {
                  ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
                }
                if (!(end < 97 || start > 122)) {
                  ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
                }
              }
            }
          }
      
          // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
          // -> [[1, 12], [14, 14], [16, 17]]
          ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1]  - a[1]); });
          var consolidatedRanges = [];
          var lastRange = [];
          for (var i = 0; i < ranges.length; ++i) {
            var range = ranges[i];
            if (range[0] <= lastRange[1] + 1) {
              lastRange[1] = Math.max(lastRange[1], range[1]);
            } else {
              consolidatedRanges.push(lastRange = range);
            }
          }
      
          for (var i = 0; i < consolidatedRanges.length; ++i) {
            var range = consolidatedRanges[i];
            out.push(encodeEscape(range[0]));
            if (range[1] > range[0]) {
              if (range[1] + 1 > range[0]) { out.push('-'); }
              out.push(encodeEscape(range[1]));
            }
          }
          out.push(']');
          return out.join('');
        }
      
        function allowAnywhereFoldCaseAndRenumberGroups(regex) {
          // Split into character sets, escape sequences, punctuation strings
          // like ('(', '(?:', ')', '^'), and runs of characters that do not
          // include any of the above.
          var parts = regex.source.match(
              new RegExp(
                  '(?:'
                  + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]'  // a character set
                  + '|\\\\u[A-Fa-f0-9]{4}'  // a unicode escape
                  + '|\\\\x[A-Fa-f0-9]{2}'  // a hex escape
                  + '|\\\\[0-9]+'  // a back-reference or octal escape
                  + '|\\\\[^ux0-9]'  // other escape sequence
                  + '|\\(\\?[:!=]'  // start of a non-capturing group
                  + '|[\\(\\)\\^]'  // start/end of a group, or line start
                  + '|[^\\x5B\\x5C\\(\\)\\^]+'  // run of other characters
                  + ')',
                  'g'));
          var n = parts.length;
      
          // Maps captured group numbers to the number they will occupy in
          // the output or to -1 if that has not been determined, or to
          // undefined if they need not be capturing in the output.
          var capturedGroups = [];
      
          // Walk over and identify back references to build the capturedGroups
          // mapping.
          for (var i = 0, groupIndex = 0; i < n; ++i) {
            var p = parts[i];
            if (p === '(') {
              // groups are 1-indexed, so max group index is count of '('
              ++groupIndex;
            } else if ('\\' === p.charAt(0)) {
              var decimalValue = +p.substring(1);
              if (decimalValue) {
                if (decimalValue <= groupIndex) {
                  capturedGroups[decimalValue] = -1;
                } else {
                  // Replace with an unambiguous escape sequence so that
                  // an octal escape sequence does not turn into a backreference
                  // to a capturing group from an earlier regex.
                  parts[i] = encodeEscape(decimalValue);
                }
              }
            }
          }
      
          // Renumber groups and reduce capturing groups to non-capturing groups
          // where possible.
          for (var i = 1; i < capturedGroups.length; ++i) {
            if (-1 === capturedGroups[i]) {
              capturedGroups[i] = ++capturedGroupIndex;
            }
          }
          for (var i = 0, groupIndex = 0; i < n; ++i) {
            var p = parts[i];
            if (p === '(') {
              ++groupIndex;
              if (!capturedGroups[groupIndex]) {
                parts[i] = '(?:';
              }
            } else if ('\\' === p.charAt(0)) {
              var decimalValue = +p.substring(1);
              if (decimalValue && decimalValue <= groupIndex) {
                parts[i] = '\\' + capturedGroups[decimalValue];
              }
            }
          }
      
          // Remove any prefix anchors so that the output will match anywhere.
          // ^^ really does mean an anchored match though.
          for (var i = 0; i < n; ++i) {
            if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
          }
      
          // Expand letters to groups to handle mixing of case-sensitive and
          // case-insensitive patterns if necessary.
          if (regex.ignoreCase && needToFoldCase) {
            for (var i = 0; i < n; ++i) {
              var p = parts[i];
              var ch0 = p.charAt(0);
              if (p.length >= 2 && ch0 === '[') {
                parts[i] = caseFoldCharset(p);
              } else if (ch0 !== '\\') {
                // TODO: handle letters in numeric escapes.
                parts[i] = p.replace(
                    /[a-zA-Z]/g,
                    function (ch) {
                      var cc = ch.charCodeAt(0);
                      return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
                    });
              }
            }
          }
      
          return parts.join('');
        }
      
        var rewritten = [];
        for (var i = 0, n = regexs.length; i < n; ++i) {
          var regex = regexs[i];
          if (regex.global || regex.multiline) { throw new Error('' + regex); }
          rewritten.push(
              '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
        }
      
        return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
      }
    
      /**
       * Split markup into a string of source code and an array mapping ranges in
       * that string to the text nodes in which they appear.
       *
       * <p>
       * The HTML DOM structure:</p>
       * <pre>
       * (Element   "p"
       *   (Element "b"
       *     (Text  "print "))       ; #1
       *   (Text    "'Hello '")      ; #2
       *   (Element "br")            ; #3
       *   (Text    "  + 'World';")) ; #4
       * </pre>
       * <p>
       * corresponds to the HTML
       * {@code <p><b>print </b>'Hello '<br>  + 'World';</p>}.</p>
       *
       * <p>
       * It will produce the output:</p>
       * <pre>
       * {
       *   sourceCode: "print 'Hello '\n  + 'World';",
       *   //                     1          2
       *   //           012345678901234 5678901234567
       *   spans: [0, #1, 6, #2, 14, #3, 15, #4]
       * }
       * </pre>
       * <p>
       * where #1 is a reference to the {@code "print "} text node above, and so
       * on for the other text nodes.
       * </p>
       *
       * <p>
       * The {@code} spans array is an array of pairs.  Even elements are the start
       * indices of substrings, and odd elements are the text nodes (or BR elements)
       * that contain the text for those substrings.
       * Substrings continue until the next index or the end of the source.
       * </p>
       *
       * @param {Node} node an HTML DOM subtree containing source-code.
       * @param {boolean} isPreformatted true if white-space in text nodes should
       *    be considered significant.
       * @return {Object} source code and the text nodes in which they occur.
       */
      function extractSourceSpans(node, isPreformatted) {
        var nocode = /(?:^|\s)nocode(?:\s|$)/;
      
        var chunks = [];
        var length = 0;
        var spans = [];
        var k = 0;
      
        function walk(node) {
          var type = node.nodeType;
          if (type == 1) {  // Element
            if (nocode.test(node.className)) { return; }
            for (var child = node.firstChild; child; child = child.nextSibling) {
              walk(child);
            }
            var nodeName = node.nodeName.toLowerCase();
            if ('br' === nodeName || 'li' === nodeName) {
              chunks[k] = '\n';
              spans[k << 1] = length++;
              spans[(k++ << 1) | 1] = node;
            }
          } else if (type == 3 || type == 4) {  // Text
            var text = node.nodeValue;
            if (text.length) {
              if (!isPreformatted) {
                text = text.replace(/[ \t\r\n]+/g, ' ');
              } else {
                text = text.replace(/\r\n?/g, '\n');  // Normalize newlines.
              }
              // TODO: handle tabs here?
              chunks[k] = text;
              spans[k << 1] = length;
              length += text.length;
              spans[(k++ << 1) | 1] = node;
            }
          }
        }
      
        walk(node);
      
        return {
          sourceCode: chunks.join('').replace(/\n$/, ''),
          spans: spans
        };
      }
    
      /**
       * Apply the given language handler to sourceCode and add the resulting
       * decorations to out.
       * @param {number} basePos the index of sourceCode within the chunk of source
       *    whose decorations are already present on out.
       */
      function appendDecorations(basePos, sourceCode, langHandler, out) {
        if (!sourceCode) { return; }
        var job = {
          sourceCode: sourceCode,
          basePos: basePos
        };
        langHandler(job);
        out.push.apply(out, job.decorations);
      }
    
      var notWs = /\S/;
    
      /**
       * Given an element, if it contains only one child element and any text nodes
       * it contains contain only space characters, return the sole child element.
       * Otherwise returns undefined.
       * <p>
       * This is meant to return the CODE element in {@code <pre><code ...>} when
       * there is a single child element that contains all the non-space textual
       * content, but not to return anything where there are multiple child elements
       * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
       * is textual content.
       */
      function childContentWrapper(element) {
        var wrapper = undefined;
        for (var c = element.firstChild; c; c = c.nextSibling) {
          var type = c.nodeType;
          wrapper = (type === 1)  // Element Node
              ? (wrapper ? element : c)
              : (type === 3)  // Text Node
              ? (notWs.test(c.nodeValue) ? element : wrapper)
              : wrapper;
        }
        return wrapper === element ? undefined : wrapper;
      }
    
      /** Given triples of [style, pattern, context] returns a lexing function,
        * The lexing function interprets the patterns to find token boundaries and
        * returns a decoration list of the form
        * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
        * where index_n is an index into the sourceCode, and style_n is a style
        * constant like PR_PLAIN.  index_n-1 <= index_n, and style_n-1 applies to
        * all characters in sourceCode[index_n-1:index_n].
        *
        * The stylePatterns is a list whose elements have the form
        * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
        *
        * Style is a style constant like PR_PLAIN, or can be a string of the
        * form 'lang-FOO', where FOO is a language extension describing the
        * language of the portion of the token in $1 after pattern executes.
        * E.g., if style is 'lang-lisp', and group 1 contains the text
        * '(hello (world))', then that portion of the token will be passed to the
        * registered lisp handler for formatting.
        * The text before and after group 1 will be restyled using this decorator
        * so decorators should take care that this doesn't result in infinite
        * recursion.  For example, the HTML lexer rule for SCRIPT elements looks
        * something like ['lang-js', /<[s]cript>(.+?)<\/script>/].  This may match
        * '<script>foo()<\/script>', which would cause the current decorator to
        * be called with '<script>' which would not match the same rule since
        * group 1 must not be empty, so it would be instead styled as PR_TAG by
        * the generic tag rule.  The handler registered for the 'js' extension would
        * then be called with 'foo()', and finally, the current decorator would
        * be called with '<\/script>' which would not match the original rule and
        * so the generic tag rule would identify it as a tag.
        *
        * Pattern must only match prefixes, and if it matches a prefix, then that
        * match is considered a token with the same style.
        *
        * Context is applied to the last non-whitespace, non-comment token
        * recognized.
        *
        * Shortcut is an optional string of characters, any of which, if the first
        * character, gurantee that this pattern and only this pattern matches.
        *
        * @param {Array} shortcutStylePatterns patterns that always start with
        *   a known character.  Must have a shortcut string.
        * @param {Array} fallthroughStylePatterns patterns that will be tried in
        *   order if the shortcut ones fail.  May have shortcuts.
        *
        * @return {function (Object)} a
        *   function that takes source code and returns a list of decorations.
        */
      function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
        var shortcuts = {};
        var tokenizer;
        (function () {
          var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
          var allRegexs = [];
          var regexKeys = {};
          for (var i = 0, n = allPatterns.length; i < n; ++i) {
            var patternParts = allPatterns[i];
            var shortcutChars = patternParts[3];
            if (shortcutChars) {
              for (var c = shortcutChars.length; --c >= 0;) {
                shortcuts[shortcutChars.charAt(c)] = patternParts;
              }
            }
            var regex = patternParts[1];
            var k = '' + regex;
            if (!regexKeys.hasOwnProperty(k)) {
              allRegexs.push(regex);
              regexKeys[k] = null;
            }
          }
          allRegexs.push(/[\0-\uffff]/);
          tokenizer = combinePrefixPatterns(allRegexs);
        })();
    
        var nPatterns = fallthroughStylePatterns.length;
    
        /**
         * Lexes job.sourceCode and produces an output array job.decorations of
         * style classes preceded by the position at which they start in
         * job.sourceCode in order.
         *
         * @param {Object} job an object like <pre>{
         *    sourceCode: {string} sourceText plain text,
         *    basePos: {int} position of job.sourceCode in the larger chunk of
         *        sourceCode.
         * }</pre>
         */
        var decorate = function (job) {
          var sourceCode = job.sourceCode, basePos = job.basePos;
          /** Even entries are positions in source in ascending order.  Odd enties
            * are style markers (e.g., PR_COMMENT) that run from that position until
            * the end.
            * @type {Array.<number|string>}
            */
          var decorations = [basePos, PR_PLAIN];
          var pos = 0;  // index into sourceCode
          var tokens = sourceCode.match(tokenizer) || [];
          var styleCache = {};
    
          for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
            var token = tokens[ti];
            var style = styleCache[token];
            var match = void 0;
    
            var isEmbedded;
            if (typeof style === 'string') {
              isEmbedded = false;
            } else {
              var patternParts = shortcuts[token.charAt(0)];
              if (patternParts) {
                match = token.match(patternParts[1]);
                style = patternParts[0];
              } else {
                for (var i = 0; i < nPatterns; ++i) {
                  patternParts = fallthroughStylePatterns[i];
                  match = token.match(patternParts[1]);
                  if (match) {
                    style = patternParts[0];
                    break;
                  }
                }
    
                if (!match) {  // make sure that we make progress
                  style = PR_PLAIN;
                }
              }
    
              isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
              if (isEmbedded && !(match && typeof match[1] === 'string')) {
                isEmbedded = false;
                style = PR_SOURCE;
              }
    
              if (!isEmbedded) { styleCache[token] = style; }
            }
    
            var tokenStart = pos;
            pos += token.length;
    
            if (!isEmbedded) {
              decorations.push(basePos + tokenStart, style);
            } else {  // Treat group 1 as an embedded block of source code.
              var embeddedSource = match[1];
              var embeddedSourceStart = token.indexOf(embeddedSource);
              var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
              if (match[2]) {
                // If embeddedSource can be blank, then it would match at the
                // beginning which would cause us to infinitely recurse on the
                // entire token, so we catch the right context in match[2].
                embeddedSourceEnd = token.length - match[2].length;
                embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
              }
              var lang = style.substring(5);
              // Decorate the left of the embedded source
              appendDecorations(
                  basePos + tokenStart,
                  token.substring(0, embeddedSourceStart),
                  decorate, decorations);
              // Decorate the embedded source
              appendDecorations(
                  basePos + tokenStart + embeddedSourceStart,
                  embeddedSource,
                  langHandlerForExtension(lang, embeddedSource),
                  decorations);
              // Decorate the right of the embedded section
              appendDecorations(
                  basePos + tokenStart + embeddedSourceEnd,
                  token.substring(embeddedSourceEnd),
                  decorate, decorations);
            }
          }
          job.decorations = decorations;
        };
        return decorate;
      }
    
      /** returns a function that produces a list of decorations from source text.
        *
        * This code treats ", ', and ` as string delimiters, and \ as a string
        * escape.  It does not recognize perl's qq() style strings.
        * It has no special handling for double delimiter escapes as in basic, or
        * the tripled delimiters used in python, but should work on those regardless
        * although in those cases a single string literal may be broken up into
        * multiple adjacent string literals.
        *
        * It recognizes C, C++, and shell style comments.
        *
        * @param {Object} options a set of optional parameters.
        * @return {function (Object)} a function that examines the source code
        *     in the input job and builds the decoration list.
        */
      function sourceDecorator(options) {
        var shortcutStylePatterns = [], fallthroughStylePatterns = [];
        if (options['tripleQuotedStrings']) {
          // '''multi-line-string''', 'single-line-string', and double-quoted
          shortcutStylePatterns.push(
              [PR_STRING,  /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
               null, '\'"']);
        } else if (options['multiLineStrings']) {
          // 'multi-line-string', "multi-line-string"
          shortcutStylePatterns.push(
              [PR_STRING,  /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
               null, '\'"`']);
        } else {
          // 'single-line-string', "single-line-string"
          shortcutStylePatterns.push(
              [PR_STRING,
               /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
               null, '"\'']);
        }
        if (options['verbatimStrings']) {
          // verbatim-string-literal production from the C# grammar.  See issue 93.
          fallthroughStylePatterns.push(
              [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
        }
        var hc = options['hashComments'];
        if (hc) {
          if (options['cStyleComments']) {
            if (hc > 1) {  // multiline hash comments
              shortcutStylePatterns.push(
                  [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
            } else {
              // Stop C preprocessor declarations at an unclosed open comment
              shortcutStylePatterns.push(
                  [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
                   null, '#']);
            }
            // #include <stdio.h>
            fallthroughStylePatterns.push(
                [PR_STRING,
                 /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
                 null]);
          } else {
            shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
          }
        }
        if (options['cStyleComments']) {
          fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
          fallthroughStylePatterns.push(
              [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
        }
        var regexLiterals = options['regexLiterals'];
        if (regexLiterals) {
          /**
           * @const
           */
          var regexExcls = regexLiterals > 1
            ? ''  // Multiline regex literals
            : '\n\r';
          /**
           * @const
           */
          var regexAny = regexExcls ? '.' : '[\\S\\s]';
          /**
           * @const
           */
          var REGEX_LITERAL = (
              // A regular expression literal starts with a slash that is
              // not followed by * or / so that it is not confused with
              // comments.
              '/(?=[^/*' + regexExcls + '])'
              // and then contains any number of raw characters,
              + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
              // escape sequences (\x5C),
              +    '|\\x5C' + regexAny
              // or non-nesting character sets (\x5B\x5D);
              +    '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
              +             '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
              // finally closed by a /.
              + '/');
          fallthroughStylePatterns.push(
              ['lang-regex',
               RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
               ]);
        }
    
        var types = options['types'];
        if (types) {
          fallthroughStylePatterns.push([PR_TYPE, types]);
        }
    
        var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
        if (keywords.length) {
          fallthroughStylePatterns.push(
              [PR_KEYWORD,
               new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
               null]);
        }
    
        shortcutStylePatterns.push([PR_PLAIN,       /^\s+/, null, ' \r\n\t\xA0']);
    
        var punctuation =
          // The Bash man page says
    
          // A word is a sequence of characters considered as a single
          // unit by GRUB. Words are separated by metacharacters,
          // which are the following plus space, tab, and newline: { }
          // | & $ ; < >
          // ...
          
          // A word beginning with # causes that word and all remaining
          // characters on that line to be ignored.
    
          // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
          // comment but empirically
          // $ echo {#}
          // {#}
          // $ echo \$#
          // $#
          // $ echo }#
          // }#
    
          // so /(?:^|[|&;<>\s])/ is more appropriate.
    
          // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
          // suggests that this definition is compatible with a
          // default mode that tries to use a single token definition
          // to recognize both bash/python style comments and C
          // preprocessor directives.
    
          // This definition of punctuation does not include # in the list of
          // follow-on exclusions, so # will not be broken before if preceeded
          // by a punctuation character.  We could try to exclude # after
          // [|&;<>] but that doesn't seem to cause many major problems.
          // If that does turn out to be a problem, we should change the below
          // when hc is truthy to include # in the run of punctuation characters
          // only when not followint [|&;<>].
          '^.[^\\s\\w.$@\'"`/\\\\]*';
        if (options['regexLiterals']) {
          punctuation += '(?!\s*\/)';
        }
    
        fallthroughStylePatterns.push(
            // TODO(mikesamuel): recognize non-latin letters and numerals in idents
            [PR_LITERAL,     /^@[a-z_$][a-z_$@0-9]*/i, null],
            [PR_TYPE,        /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
            [PR_PLAIN,       /^[a-z_$][a-z_$@0-9]*/i, null],
            [PR_LITERAL,
             new RegExp(
                 '^(?:'
                 // A hex number
                 + '0x[a-f0-9]+'
                 // or an octal or decimal number,
                 + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
                 // possibly in scientific notation
                 + '(?:e[+\\-]?\\d+)?'
                 + ')'
                 // with an optional modifier like UL for unsigned long
                 + '[a-z]*', 'i'),
             null, '0123456789'],
            // Don't treat escaped quotes in bash as starting strings.
            // See issue 144.
            [PR_PLAIN,       /^\\[\s\S]?/, null],
            [PR_PUNCTUATION, new RegExp(punctuation), null]);
    
        return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
      }
    
      var decorateSource = sourceDecorator({
            'keywords': ALL_KEYWORDS,
            'hashComments': true,
            'cStyleComments': true,
            'multiLineStrings': true,
            'regexLiterals': true
          });
    
      /**
       * Given a DOM subtree, wraps it in a list, and puts each line into its own
       * list item.
       *
       * @param {Node} node modified in place.  Its content is pulled into an
       *     HTMLOListElement, and each line is moved into a separate list item.
       *     This requires cloning elements, so the input might not have unique
       *     IDs after numbering.
       * @param {boolean} isPreformatted true iff white-space in text nodes should
       *     be treated as significant.
       */
      function numberLines(node, opt_startLineNum, isPreformatted) {
        var nocode = /(?:^|\s)nocode(?:\s|$)/;
        var lineBreak = /\r\n?|\n/;
      
        var document = node.ownerDocument;
      
        var li = document.createElement('li');
        while (node.firstChild) {
          li.appendChild(node.firstChild);
        }
        // An array of lines.  We split below, so this is initialized to one
        // un-split line.
        var listItems = [li];
      
        function walk(node) {
          var type = node.nodeType;
          if (type == 1 && !nocode.test(node.className)) {  // Element
            if ('br' === node.nodeName) {
              breakAfter(node);
              // Discard the <BR> since it is now flush against a </LI>.
              if (node.parentNode) {
                node.parentNode.removeChild(node);
              }
            } else {
              for (var child = node.firstChild; child; child = child.nextSibling) {
                walk(child);
              }
            }
          } else if ((type == 3 || type == 4) && isPreformatted) {  // Text
            var text = node.nodeValue;
            var match = text.match(lineBreak);
            if (match) {
              var firstLine = text.substring(0, match.index);
              node.nodeValue = firstLine;
              var tail = text.substring(match.index + match[0].length);
              if (tail) {
                var parent = node.parentNode;
                parent.insertBefore(
                  document.createTextNode(tail), node.nextSibling);
              }
              breakAfter(node);
              if (!firstLine) {
                // Don't leave blank text nodes in the DOM.
                node.parentNode.removeChild(node);
              }
            }
          }
        }
      
        // Split a line after the given node.
        function breakAfter(lineEndNode) {
          // If there's nothing to the right, then we can skip ending the line
          // here, and move root-wards since splitting just before an end-tag
          // would require us to create a bunch of empty copies.
          while (!lineEndNode.nextSibling) {
            lineEndNode = lineEndNode.parentNode;
            if (!lineEndNode) { return; }
          }
      
          function breakLeftOf(limit, copy) {
            // Clone shallowly if this node needs to be on both sides of the break.
            var rightSide = copy ? limit.cloneNode(false) : limit;
            var parent = limit.parentNode;
            if (parent) {
              // We clone the parent chain.
              // This helps us resurrect important styling elements that cross lines.
              // E.g. in <i>Foo<br>Bar</i>
              // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
              var parentClone = breakLeftOf(parent, 1);
              // Move the clone and everything to the right of the original
              // onto the cloned parent.
              var next = limit.nextSibling;
              parentClone.appendChild(rightSide);
              for (var sibling = next; sibling; sibling = next) {
                next = sibling.nextSibling;
                parentClone.appendChild(sibling);
              }
            }
            return rightSide;
          }
      
          var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
      
          // Walk the parent chain until we reach an unattached LI.
          for (var parent;
               // Check nodeType since IE invents document fragments.
               (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
            copiedListItem = parent;
          }
          // Put it on the list of lines for later processing.
          listItems.push(copiedListItem);
        }
      
        // Split lines while there are lines left to split.
        for (var i = 0;  // Number of lines that have been split so far.
             i < listItems.length;  // length updated by breakAfter calls.
             ++i) {
          walk(listItems[i]);
        }
      
        // Make sure numeric indices show correctly.
        if (opt_startLineNum === (opt_startLineNum|0)) {
          listItems[0].setAttribute('value', opt_startLineNum);
        }
      
        var ol = document.createElement('ol');
        ol.className = 'linenums';
        var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
        for (var i = 0, n = listItems.length; i < n; ++i) {
          li = listItems[i];
          // Stick a class on the LIs so that stylesheets can
          // color odd/even rows, or any other row pattern that
          // is co-prime with 10.
          li.className = 'L' + ((i + offset) % 10);
          if (!li.firstChild) {
            li.appendChild(document.createTextNode('\xA0'));
          }
          ol.appendChild(li);
        }
      
        node.appendChild(ol);
      }
      /**
       * Breaks {@code job.sourceCode} around style boundaries in
       * {@code job.decorations} and modifies {@code job.sourceNode} in place.
       * @param {Object} job like <pre>{
       *    sourceCode: {string} source as plain text,
       *    sourceNode: {HTMLElement} the element containing the source,
       *    spans: {Array.<number|Node>} alternating span start indices into source
       *       and the text node or element (e.g. {@code <BR>}) corresponding to that
       *       span.
       *    decorations: {Array.<number|string} an array of style classes preceded
       *       by the position at which they start in job.sourceCode in order
       * }</pre>
       * @private
       */
      function recombineTagsAndDecorations(job) {
        var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
        isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
        var newlineRe = /\n/g;
      
        var source = job.sourceCode;
        var sourceLength = source.length;
        // Index into source after the last code-unit recombined.
        var sourceIndex = 0;
      
        var spans = job.spans;
        var nSpans = spans.length;
        // Index into spans after the last span which ends at or before sourceIndex.
        var spanIndex = 0;
      
        var decorations = job.decorations;
        var nDecorations = decorations.length;
        // Index into decorations after the last decoration which ends at or before
        // sourceIndex.
        var decorationIndex = 0;
      
        // Remove all zero-length decorations.
        decorations[nDecorations] = sourceLength;
        var decPos, i;
        for (i = decPos = 0; i < nDecorations;) {
          if (decorations[i] !== decorations[i + 2]) {
            decorations[decPos++] = decorations[i++];
            decorations[decPos++] = decorations[i++];
          } else {
            i += 2;
          }
        }
        nDecorations = decPos;
      
        // Simplify decorations.
        for (i = decPos = 0; i < nDecorations;) {
          var startPos = decorations[i];
          // Conflate all adjacent decorations that use the same style.
          var startDec = decorations[i + 1];
          var end = i + 2;
          while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
            end += 2;
          }
          decorations[decPos++] = startPos;
          decorations[decPos++] = startDec;
          i = end;
        }
      
        nDecorations = decorations.length = decPos;
      
        var sourceNode = job.sourceNode;
        var oldDisplay;
        if (sourceNode) {
          oldDisplay = sourceNode.style.display;
          sourceNode.style.display = 'none';
        }
        try {
          var decoration = null;
          while (spanIndex < nSpans) {
            var spanStart = spans[spanIndex];
            var spanEnd = spans[spanIndex + 2] || sourceLength;
      
            var decEnd = decorations[decorationIndex + 2] || sourceLength;
      
            var end = Math.min(spanEnd, decEnd);
      
            var textNode = spans[spanIndex + 1];
            var styledText;
            if (textNode.nodeType !== 1  // Don't muck with <BR>s or <LI>s
                // Don't introduce spans around empty text nodes.
                && (styledText = source.substring(sourceIndex, end))) {
              // This may seem bizarre, and it is.  Emitting LF on IE causes the
              // code to display with spaces instead of line breaks.
              // Emitting Windows standard issue linebreaks (CRLF) causes a blank
              // space to appear at the beginning of every line but the first.
              // Emitting an old Mac OS 9 line separator makes everything spiffy.
              if (isIE8OrEarlier) {
                styledText = styledText.replace(newlineRe, '\r');
              }
              textNode.nodeValue = styledText;
              var document = textNode.ownerDocument;
              var span = document.createElement('span');
              span.className = decorations[decorationIndex + 1];
              var parentNode = textNode.parentNode;
              parentNode.replaceChild(span, textNode);
              span.appendChild(textNode);
              if (sourceIndex < spanEnd) {  // Split off a text node.
                spans[spanIndex + 1] = textNode
                    // TODO: Possibly optimize by using '' if there's no flicker.
                    = document.createTextNode(source.substring(end, spanEnd));
                parentNode.insertBefore(textNode, span.nextSibling);
              }
            }
      
            sourceIndex = end;
      
            if (sourceIndex >= spanEnd) {
              spanIndex += 2;
            }
            if (sourceIndex >= decEnd) {
              decorationIndex += 2;
            }
          }
        } finally {
          if (sourceNode) {
            sourceNode.style.display = oldDisplay;
          }
        }
      }
    
      /** Maps language-specific file extensions to handlers. */
      var langHandlerRegistry = {};
      /** Register a language handler for the given file extensions.
        * @param {function (Object)} handler a function from source code to a list
        *      of decorations.  Takes a single argument job which describes the
        *      state of the computation.   The single parameter has the form
        *      {@code {
        *        sourceCode: {string} as plain text.
        *        decorations: {Array.<number|string>} an array of style classes
        *                     preceded by the position at which they start in
        *                     job.sourceCode in order.
        *                     The language handler should assigned this field.
        *        basePos: {int} the position of source in the larger source chunk.
        *                 All positions in the output decorations array are relative
        *                 to the larger source chunk.
        *      } }
        * @param {Array.<string>} fileExtensions
        */
      function registerLangHandler(handler, fileExtensions) {
        for (var i = fileExtensions.length; --i >= 0;) {
          var ext = fileExtensions[i];
          if (!langHandlerRegistry.hasOwnProperty(ext)) {
            langHandlerRegistry[ext] = handler;
          } else if (win['console']) {
            console['warn']('cannot override language handler %s', ext);
          }
        }
      }
      function langHandlerForExtension(extension, source) {
        if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
          // Treat it as markup if the first non whitespace character is a < and
          // the last non-whitespace character is a >.
          extension = /^\s*</.test(source)
              ? 'default-markup'
              : 'default-code';
        }
        return langHandlerRegistry[extension];
      }
      registerLangHandler(decorateSource, ['default-code']);
      registerLangHandler(
          createSimpleLexer(
              [],
              [
               [PR_PLAIN,       /^[^<?]+/],
               [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
               [PR_COMMENT,     /^<\!--[\s\S]*?(?:-\->|$)/],
               // Unescaped content in an unknown language
               ['lang-',        /^<\?([\s\S]+?)(?:\?>|$)/],
               ['lang-',        /^<%([\s\S]+?)(?:%>|$)/],
               [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
               ['lang-',        /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
               // Unescaped content in javascript.  (Or possibly vbscript).
               ['lang-js',      /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
               // Contains unescaped stylesheet content
               ['lang-css',     /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
               ['lang-in.tag',  /^(<\/?[a-z][^<>]*>)/i]
              ]),
          ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
      registerLangHandler(
          createSimpleLexer(
              [
               [PR_PLAIN,        /^[\s]+/, null, ' \t\r\n'],
               [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
               ],
              [
               [PR_TAG,          /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
               [PR_ATTRIB_NAME,  /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
               ['lang-uq.val',   /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
               [PR_PUNCTUATION,  /^[=<>\/]+/],
               ['lang-js',       /^on\w+\s*=\s*\"([^\"]+)\"/i],
               ['lang-js',       /^on\w+\s*=\s*\'([^\']+)\'/i],
               ['lang-js',       /^on\w+\s*=\s*([^\"\'>\s]+)/i],
               ['lang-css',      /^style\s*=\s*\"([^\"]+)\"/i],
               ['lang-css',      /^style\s*=\s*\'([^\']+)\'/i],
               ['lang-css',      /^style\s*=\s*([^\"\'>\s]+)/i]
               ]),
          ['in.tag']);
      registerLangHandler(
          createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
      registerLangHandler(sourceDecorator({
              'keywords': CPP_KEYWORDS,
              'hashComments': true,
              'cStyleComments': true,
              'types': C_TYPES
            }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
      registerLangHandler(sourceDecorator({
              'keywords': 'null,true,false'
            }), ['json']);
      registerLangHandler(sourceDecorator({
              'keywords': CSHARP_KEYWORDS,
              'hashComments': true,
              'cStyleComments': true,
              'verbatimStrings': true,
              'types': C_TYPES
            }), ['cs']);
      registerLangHandler(sourceDecorator({
              'keywords': JAVA_KEYWORDS,
              'cStyleComments': true
            }), ['java']);
      registerLangHandler(sourceDecorator({
              'keywords': SH_KEYWORDS,
              'hashComments': true,
              'multiLineStrings': true
            }), ['bash', 'bsh', 'csh', 'sh']);
      registerLangHandler(sourceDecorator({
              'keywords': PYTHON_KEYWORDS,
              'hashComments': true,
              'multiLineStrings': true,
              'tripleQuotedStrings': true
            }), ['cv', 'py', 'python']);
      registerLangHandler(sourceDecorator({
              'keywords': PERL_KEYWORDS,
              'hashComments': true,
              'multiLineStrings': true,
              'regexLiterals': 2  // multiline regex literals
            }), ['perl', 'pl', 'pm']);
      registerLangHandler(sourceDecorator({
              'keywords': RUBY_KEYWORDS,
              'hashComments': true,
              'multiLineStrings': true,
              'regexLiterals': true
            }), ['rb', 'ruby']);
      registerLangHandler(sourceDecorator({
              'keywords': JSCRIPT_KEYWORDS,
              'cStyleComments': true,
              'regexLiterals': true
            }), ['javascript', 'js']);
      registerLangHandler(sourceDecorator({
              'keywords': COFFEE_KEYWORDS,
              'hashComments': 3,  // ### style block comments
              'cStyleComments': true,
              'multilineStrings': true,
              'tripleQuotedStrings': true,
              'regexLiterals': true
            }), ['coffee']);
      registerLangHandler(sourceDecorator({
              'keywords': RUST_KEYWORDS,
              'cStyleComments': true,
              'multilineStrings': true
            }), ['rc', 'rs', 'rust']);
      registerLangHandler(
          createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
    
      function applyDecorator(job) {
        var opt_langExtension = job.langExtension;
    
        try {
          // Extract tags, and convert the source code to plain text.
          var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
          /** Plain text. @type {string} */
          var source = sourceAndSpans.sourceCode;
          job.sourceCode = source;
          job.spans = sourceAndSpans.spans;
          job.basePos = 0;
    
          // Apply the appropriate language handler
          langHandlerForExtension(opt_langExtension, source)(job);
    
          // Integrate the decorations and tags back into the source code,
          // modifying the sourceNode in place.
          recombineTagsAndDecorations(job);
        } catch (e) {
          if (win['console']) {
            console['log'](e && e['stack'] || e);
          }
        }
      }
    
      /**
       * Pretty print a chunk of code.
       * @param sourceCodeHtml {string} The HTML to pretty print.
       * @param opt_langExtension {string} The language name to use.
       *     Typically, a filename extension like 'cpp' or 'java'.
       * @param opt_numberLines {number|boolean} True to number lines,
       *     or the 1-indexed number of the first line in sourceCodeHtml.
       */
      function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
        var container = document.createElement('div');
        // This could cause images to load and onload listeners to fire.
        // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
        // We assume that the inner HTML is from a trusted source.
        // The pre-tag is required for IE8 which strips newlines from innerHTML
        // when it is injected into a <pre> tag.
        // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
        // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
        container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
        container = container.firstChild;
        if (opt_numberLines) {
          numberLines(container, opt_numberLines, true);
        }
    
        var job = {
          langExtension: opt_langExtension,
          numberLines: opt_numberLines,
          sourceNode: container,
          pre: 1
        };
        applyDecorator(job);
        return container.innerHTML;
      }
    
       /**
        * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
        * {@code class=prettyprint} and prettify them.
        *
        * @param {Function} opt_whenDone called when prettifying is done.
        * @param {HTMLElement|HTMLDocument} opt_root an element or document
        *   containing all the elements to pretty print.
        *   Defaults to {@code document.body}.
        */
      function $prettyPrint(opt_whenDone, opt_root) {
        var root = opt_root || document.body;
        var doc = root.ownerDocument || document;
        function byTagName(tn) { return root.getElementsByTagName(tn); }
        // fetch a list of nodes to rewrite
        var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
        var elements = [];
        for (var i = 0; i < codeSegments.length; ++i) {
          for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
            elements.push(codeSegments[i][j]);
          }
        }
        codeSegments = null;
    
        var clock = Date;
        if (!clock['now']) {
          clock = { 'now': function () { return +(new Date); } };
        }
    
        // The loop is broken into a series of continuations to make sure that we
        // don't make the browser unresponsive when rewriting a large page.
        var k = 0;
        var prettyPrintingJob;
    
        var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
        var prettyPrintRe = /\bprettyprint\b/;
        var prettyPrintedRe = /\bprettyprinted\b/;
        var preformattedTagNameRe = /pre|xmp/i;
        var codeRe = /^code$/i;
        var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
        var EMPTY = {};
    
        function doWork() {
          var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
                         clock['now']() + 250 /* ms */ :
                         Infinity);
          for (; k < elements.length && clock['now']() < endTime; k++) {
            var cs = elements[k];
    
            // Look for a preceding comment like
            // <?prettify lang="..." linenums="..."?>
            var attrs = EMPTY;
            {
              for (var preceder = cs; (preceder = preceder.previousSibling);) {
                var nt = preceder.nodeType;
                // <?foo?> is parsed by HTML 5 to a comment node (8)
                // like <!--?foo?-->, but in XML is a processing instruction
                var value = (nt === 7 || nt === 8) && preceder.nodeValue;
                if (value
                    ? !/^\??prettify\b/.test(value)
                    : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
                  // Skip over white-space text nodes but not others.
                  break;
                }
                if (value) {
                  attrs = {};
                  value.replace(
                      /\b(\w+)=([\w:.%+-]+)/g,
                    function (_, name, value) { attrs[name] = value; });
                  break;
                }
              }
            }
    
            var className = cs.className;
            if ((attrs !== EMPTY || prettyPrintRe.test(className))
                // Don't redo this if we've already done it.
                // This allows recalling pretty print to just prettyprint elements
                // that have been added to the page since last call.
                && !prettyPrintedRe.test(className)) {
    
              // make sure this is not nested in an already prettified element
              var nested = false;
              for (var p = cs.parentNode; p; p = p.parentNode) {
                var tn = p.tagName;
                if (preCodeXmpRe.test(tn)
                    && p.className && prettyPrintRe.test(p.className)) {
                  nested = true;
                  break;
                }
              }
              if (!nested) {
                // Mark done.  If we fail to prettyprint for whatever reason,
                // we shouldn't try again.
                cs.className += ' prettyprinted';
    
                // If the classes includes a language extensions, use it.
                // Language extensions can be specified like
                //     <pre class="prettyprint lang-cpp">
                // the language extension "cpp" is used to find a language handler
                // as passed to PR.registerLangHandler.
                // HTML5 recommends that a language be specified using "language-"
                // as the prefix instead.  Google Code Prettify supports both.
                // http://dev.w3.org/html5/spec-author-view/the-code-element.html
                var langExtension = attrs['lang'];
                if (!langExtension) {
                  langExtension = className.match(langExtensionRe);
                  // Support <pre class="prettyprint"><code class="language-c">
                  var wrapper;
                  if (!langExtension && (wrapper = childContentWrapper(cs))
                      && codeRe.test(wrapper.tagName)) {
                    langExtension = wrapper.className.match(langExtensionRe);
                  }
    
                  if (langExtension) { langExtension = langExtension[1]; }
                }
    
                var preformatted;
                if (preformattedTagNameRe.test(cs.tagName)) {
                  preformatted = 1;
                } else {
                  var currentStyle = cs['currentStyle'];
                  var defaultView = doc.defaultView;
                  var whitespace = (
                      currentStyle
                      ? currentStyle['whiteSpace']
                      : (defaultView
                         && defaultView.getComputedStyle)
                      ? defaultView.getComputedStyle(cs, null)
                      .getPropertyValue('white-space')
                      : 0);
                  preformatted = whitespace
                      && 'pre' === whitespace.substring(0, 3);
                }
    
                // Look for a class like linenums or linenums:<n> where <n> is the
                // 1-indexed number of the first line.
                var lineNums = attrs['linenums'];
                if (!(lineNums = lineNums === 'true' || +lineNums)) {
                  lineNums = className.match(/\blinenums\b(?::(\d+))?/);
                  lineNums =
                    lineNums
                    ? lineNums[1] && lineNums[1].length
                      ? +lineNums[1] : true
                    : false;
                }
                if (lineNums) { numberLines(cs, lineNums, preformatted); }
    
                // do the pretty printing
                prettyPrintingJob = {
                  langExtension: langExtension,
                  sourceNode: cs,
                  numberLines: lineNums,
                  pre: preformatted
                };
                applyDecorator(prettyPrintingJob);
              }
            }
          }
          if (k < elements.length) {
            // finish up in a continuation
            setTimeout(doWork, 250);
          } else if ('function' === typeof opt_whenDone) {
            opt_whenDone();
          }
        }
    
        doWork();
      }
    
      /**
       * Contains functions for creating and registering new language handlers.
       * @type {Object}
       */
      var PR = win['PR'] = {
            'createSimpleLexer': createSimpleLexer,
            'registerLangHandler': registerLangHandler,
            'sourceDecorator': sourceDecorator,
            'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
            'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
            'PR_COMMENT': PR_COMMENT,
            'PR_DECLARATION': PR_DECLARATION,
            'PR_KEYWORD': PR_KEYWORD,
            'PR_LITERAL': PR_LITERAL,
            'PR_NOCODE': PR_NOCODE,
            'PR_PLAIN': PR_PLAIN,
            'PR_PUNCTUATION': PR_PUNCTUATION,
            'PR_SOURCE': PR_SOURCE,
            'PR_STRING': PR_STRING,
            'PR_TAG': PR_TAG,
            'PR_TYPE': PR_TYPE,
            'prettyPrintOne':
               IN_GLOBAL_SCOPE
                 ? (win['prettyPrintOne'] = $prettyPrintOne)
                 : (prettyPrintOne = $prettyPrintOne),
            'prettyPrint': prettyPrint =
               IN_GLOBAL_SCOPE
                 ? (win['prettyPrint'] = $prettyPrint)
                 : (prettyPrint = $prettyPrint)
          };
    
      // Make PR available via the Asynchronous Module Definition (AMD) API.
      // Per https://github.com/amdjs/amdjs-api/wiki/AMD:
      // The Asynchronous Module Definition (AMD) API specifies a
      // mechanism for defining modules such that the module and its
      // dependencies can be asynchronously loaded.
      // ...
      // To allow a clear indicator that a global define function (as
      // needed for script src browser loading) conforms to the AMD API,
      // any global define function SHOULD have a property called "amd"
      // whose value is an object. This helps avoid conflict with any
      // other existing JavaScript code that could have defined a define()
      // function that does not conform to the AMD API.
      if (typeof define === "function" && define['amd']) {
        define("google-code-prettify", [], function () {
          return PR; 
        });
      }
    })();
    ������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-mumps.js���������������������������������������������������������������0000640�0001750�0001750�00000012305�12115200050�015600� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2011 Kitware Inc.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    
    /**
     * @fileoverview
     * Registers a language handler for MUMPS.
     *
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code in an HTML tag like
     *      <pre class="prettyprint lang-mumps">(my SQL code)</pre>
     * 
     * Commands, intrinsic functions and variables taken from ISO/IEC 11756:1999(E)
     *
     * @author chris.harris@kitware.com
     *
     * Known issues:
     * 
     * - Currently can't distinguish between keywords and local or global variables having the same name
     *   for exampe SET IF="IF?"
     * - m file are already used for MatLab hence using mumps.
     */
    
    (function () {
    
    
    var commands = 'B|BREAK|'       + 
                   'C|CLOSE|'       +
                   'D|DO|'          +
                   'E|ELSE|'        +
                   'F|FOR|'         +
                   'G|GOTO|'        +
                   'H|HALT|'        +
                   'H|HANG|'        +
                   'I|IF|'          +
                   'J|JOB|'         +
                   'K|KILL|'        +
                   'L|LOCK|'        +
                   'M|MERGE|'       +
                   'N|NEW|'         +
                   'O|OPEN|'        +     
                   'Q|QUIT|'        +
                   'R|READ|'        +
                   'S|SET|'         +
                   'TC|TCOMMIT|'    +
                   'TRE|TRESTART|'  +
                   'TRO|TROLLBACK|' +
                   'TS|TSTART|'     +
                   'U|USE|'         +
                   'V|VIEW|'        +  
                   'W|WRITE|'       +
                   'X|XECUTE';
    
    var intrinsicVariables = 'D|DEVICE|'       +
                             'EC|ECODE|'       +  
                             'ES|ESTACK|'      +
                             'ET|ETRAP|'       +
                             'H|HOROLOG|'      +
                             'I|IO|'           +
                             'J|JOB|'          +
                             'K|KEY|'          +
                             'P|PRINCIPAL|'    +
                             'Q|QUIT|'         +
                             'ST|STACK|'       +
                             'S|STORAGE|'      +
                             'SY|SYSTEM|'      +
                             'T|TEST|'         +
                             'TL|TLEVEL|'      +
                             'TR|TRESTART|'    +
                             'X|'              +
                             'Y|'              +
                             'Z[A-Z]*|';    
    
    var intrinsicFunctions = 'A|ASCII|'        +
                             'C|CHAR|'         +
                             'D|DATA|'         +
                             'E|EXTRACT|'      +
                             'F|FIND|'         +
                             'FN|FNUMBER|'     +
                             'G|GET|'          +
                             'J|JUSTIFY|'      +
                             'L|LENGTH|'       +
                             'NA|NAME|'        +
                             'O|ORDER|'        +
                             'P|PIECE|'        +
                             'QL|QLENGTH|'     +
                             'QS|QSUBSCRIPT|'  +
                             'Q|QUERY|'        +
                             'R|RANDOM|'       +
                             'RE|REVERSE|'     +
                             'S|SELECT|'       +
                             'ST|STACK|'       +
                             'T|TEXT|'         +
                             'TR|TRANSLATE|'   +
                             'V|VIEW|'         * 
                             'Z[A-Z]*|';   
    
    var intrinsic = intrinsicVariables + intrinsicFunctions;                  
    
    
    var shortcutStylePatterns = [
             // Whitespace
             [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
             // A double or single quoted, possibly multi-line, string.
             [PR['PR_STRING'],      /^(?:"(?:[^"]|\\.)*")/, null, '"']
      ];
    
    var fallthroughStylePatterns = [
             // A line comment that starts with ;
             [PR['PR_COMMENT'],     /^;[^\r\n]*/, null, ';'],
             // Add intrinsic variables and functions as declarations, there not really but it mean
             // they will hilighted differently from commands.
             [PR['PR_DECLARATION'], new RegExp('^(?:\\$(?:' + intrinsic + '))\\b', 'i'), null],
             // Add commands as keywords
             [PR['PR_KEYWORD'], new RegExp('^(?:[^\\$]' + commands + ')\\b', 'i'), null],
             // A number is a decimal real literal or in scientific notation. 
             [PR['PR_LITERAL'],
              /^[+-]?(?:(?:\.\d+|\d+(?:\.\d*)?)(?:E[+\-]?\d+)?)/i], 
             // An identifier
             [PR['PR_PLAIN'], /^[a-z][a-zA-Z0-9]*/i],
             // Exclude $ % and ^
             [PR['PR_PUNCTUATION'], /^[^\w\t\n\r\xA0\"\$;%\^]|_/]
      ];
    // Can't use m as its already used for MatLab
    PR.registerLangHandler(PR.createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns), ['mumps']);
    })();
    ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-apollo.js��������������������������������������������������������������0000640�0001750�0001750�00000005072�12115200050�015730� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2009 Onno Hommes.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    /**
     * @fileoverview
     * Registers a language handler for the AGC/AEA Assembly Language as described
     * at http://virtualagc.googlecode.com
     * <p>
     * This file could be used by goodle code to allow syntax highlight for
     * Virtual AGC SVN repository or if you don't want to commonize
     * the header for the agc/aea html assembly listing.
     *
     * @author ohommes@alumni.cmu.edu
     */
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             // A line comment that starts with ;
             [PR['PR_COMMENT'],     /^#[^\r\n]*/, null, '#'],
             // Whitespace
             [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
             // A double quoted, possibly multi-line, string.
             [PR['PR_STRING'],      /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"']
            ],
            [
             [PR['PR_KEYWORD'], /^(?:ADS|AD|AUG|BZF|BZMF|CAE|CAF|CA|CCS|COM|CS|DAS|DCA|DCOM|DCS|DDOUBL|DIM|DOUBLE|DTCB|DTCF|DV|DXCH|EDRUPT|EXTEND|INCR|INDEX|NDX|INHINT|LXCH|MASK|MSK|MP|MSU|NOOP|OVSK|QXCH|RAND|READ|RELINT|RESUME|RETURN|ROR|RXOR|SQUARE|SU|TCR|TCAA|OVSK|TCF|TC|TS|WAND|WOR|WRITE|XCH|XLQ|XXALQ|ZL|ZQ|ADD|ADZ|SUB|SUZ|MPY|MPR|MPZ|DVP|COM|ABS|CLA|CLZ|LDQ|STO|STQ|ALS|LLS|LRS|TRA|TSQ|TMI|TOV|AXT|TIX|DLY|INP|OUT)\s/,null],
             [PR['PR_TYPE'], /^(?:-?GENADR|=MINUS|2BCADR|VN|BOF|MM|-?2CADR|-?[1-6]DNADR|ADRES|BBCON|[SE]?BANK\=?|BLOCK|BNKSUM|E?CADR|COUNT\*?|2?DEC\*?|-?DNCHAN|-?DNPTR|EQUALS|ERASE|MEMORY|2?OCT|REMADR|SETLOC|SUBRO|ORG|BSS|BES|SYN|EQU|DEFINE|END)\s/,null],
             // A single quote possibly followed by a word that optionally ends with
             // = ! or ?.
             [PR['PR_LITERAL'],
              /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],
             // Any word including labels that optionally ends with = ! or ?.
             [PR['PR_PLAIN'],
              /^-*(?:[!-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],
             // A printable non-space non-special character
             [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/]
            ]),
        ['apollo', 'agc', 'aea']);
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-erlang.js��������������������������������������������������������������0000640�0001750�0001750�00000006655�12115200050�015722� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2013 Andrew Allen
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    /**
     * @fileoverview
     * Registers a language handler for Erlang.
     *
     * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl
     * Modified from Mike Samuel's Haskell plugin for google-code-prettify
     *
     * @author achew22@gmail.com
     */
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             // Whitespace
             // whitechar    ->    newline | vertab | space | tab | uniWhite
             // newline      ->    return linefeed | return | linefeed | formfeed
             [PR['PR_PLAIN'],       /^[\t\n\x0B\x0C\r ]+/, null, '\t\n\x0B\x0C\r '],
             // Single line double-quoted strings.
             [PR['PR_STRING'],      /^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/,
              null, '"'],
             
             // Handle atoms
             [PR['PR_LITERAL'],      /^[a-z][a-zA-Z0-9_]*/],
             // Handle single quoted atoms
             [PR['PR_LITERAL'],      /^\'(?:[^\'\\\n\x0C\r]|\\[^&])+\'?/,
              null, "'"],
             
             // Handle macros. Just to be extra clear on this one, it detects the ?
             // then uses the regexp to end it so be very careful about matching
             // all the terminal elements
             [PR['PR_LITERAL'],      /^\?[^ \t\n({]+/, null, "?"],
    
              
             
             // decimal      ->    digit{digit}
             // octal        ->    octit{octit}
             // hexadecimal  ->    hexit{hexit}
             // integer      ->    decimal
             //               |    0o octal | 0O octal
             //               |    0x hexadecimal | 0X hexadecimal
             // float        ->    decimal . decimal [exponent]
             //               |    decimal exponent
             // exponent     ->    (e | E) [+ | -] decimal
             [PR['PR_LITERAL'],
              /^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i,
              null, '0123456789']
            ],
            [
             // TODO: catch @declarations inside comments
    
             // Comments in erlang are started with % and go till a newline
             [PR['PR_COMMENT'], /^%[^\n]*/],
    
             // Catch macros
             //[PR['PR_TAG'], /?[^( \n)]+/],
    
             /**
              * %% Keywords (atoms are assumed to always be single-quoted).
              * 'module' 'attributes' 'do' 'let' 'in' 'letrec'
              * 'apply' 'call' 'primop'
              * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after'
              */
             [PR['PR_KEYWORD'], /^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\b/],
             
             /**
              * Catch definitions (usually defined at the top of the file)
              * Anything that starts -something
              */
             [PR['PR_KEYWORD'], /^-[a-z_]+/],
    
             // Catch variables
             [PR['PR_TYPE'], /^[A-Z_][a-zA-Z0-9_]*/],
    
             // matches the symbol production
             [PR['PR_PUNCTUATION'], /^[.,;]/]
            ]),
        ['erlang', 'erl']);
    �����������������������������������������������������������������������������������prettify-2013.03.04/src/lang-lisp.js����������������������������������������������������������������0000640�0001750�0001750�00000007056�12115200050�015415� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2008 Google Inc.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    
    /**
     * @fileoverview
     * Registers a language handler for Common Lisp and related languages.
     *
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code in an HTML tag like
     *      <pre class="prettyprint lang-lisp">(my lisp code)</pre>
     * The lang-cl class identifies the language as common lisp.
     * This file supports the following language extensions:
     *     lang-cl - Common Lisp
     *     lang-el - Emacs Lisp
     *     lang-lisp - Lisp
     *     lang-scm - Scheme
     *     lang-lsp - FAT 8.3 filename version of lang-lisp.
     *
     *
     * I used http://www.devincook.com/goldparser/doc/meta-language/grammar-LISP.htm
     * as the basis, but added line comments that start with ; and changed the atom
     * production to disallow unquoted semicolons.
     *
     * "Name"    = 'LISP'
     * "Author"  = 'John McCarthy'
     * "Version" = 'Minimal'
     * "About"   = 'LISP is an abstract language that organizes ALL'
     *           | 'data around "lists".'
     *
     * "Start Symbol" = [s-Expression]
     *
     * {Atom Char}   = {Printable} - {Whitespace} - [()"\'']
     *
     * Atom = ( {Atom Char} | '\'{Printable} )+
     *
     * [s-Expression] ::= [Quote] Atom
     *                  | [Quote] '(' [Series] ')'
     *                  | [Quote] '(' [s-Expression] '.' [s-Expression] ')'
     *
     * [Series] ::= [s-Expression] [Series]
     *            |
     *
     * [Quote]  ::= ''      !Quote = do not evaluate
     *            |
     *
     *
     * I used <a href="http://gigamonkeys.com/book/">Practical Common Lisp</a> as
     * the basis for the reserved word list.
     *
     *
     * @author mikesamuel@gmail.com
     */
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             ['opn',             /^\(+/, null, '('],
             ['clo',             /^\)+/, null, ')'],
             // A line comment that starts with ;
             [PR['PR_COMMENT'],     /^;[^\r\n]*/, null, ';'],
             // Whitespace
             [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
             // A double quoted, possibly multi-line, string.
             [PR['PR_STRING'],      /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"']
            ],
            [
             [PR['PR_KEYWORD'],     /^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/, null],
             [PR['PR_LITERAL'],
              /^[+\-]?(?:[0#]x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i],
             // A single quote possibly followed by a word that optionally ends with
             // = ! or ?.
             [PR['PR_LITERAL'],
              /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],
             // A word that optionally ends with = ! or ?.
             [PR['PR_PLAIN'],
              /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],
             // A printable non-space non-special character
             [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/]
            ]),
        ['cl', 'el', 'lisp', 'lsp', 'scm', 'ss', 'rkt']);
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-xq.js������������������������������������������������������������������0000640�0001750�0001750�00000061537�12115200050�015102� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2011 Patrick Wied
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    
    /**
     * @fileoverview
     * Registers a language handler for XQuery.
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code in an HTML tag like
     *      <pre class="prettyprint lang-xq"></pre>
     *
     *
     * @author Patrick Wied ( patpa7p@live.de )
     * @version 2010-09-28
     */
    
    // Falls back to plain for stylesheets that don't style fun.
    var PR_FUNCTION = 'fun pln';
    // Falls back to plaiin for stylesheets that don't style var.
    var PR_VARIABLE = 'var pln';
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             // Matching $var-ia_bles
             [PR_VARIABLE, /^\$[A-Za-z0-9_\-]+/, null, "$"]
            ],
            [
             // Matching lt and gt operators
             // Not the best matching solution but you have to differentiate between the gt operator and the tag closing char
             [PR['PR_PLAIN'], /^[\s=][<>][\s=]/],
             // Matching @Attributes
             [PR['PR_LITERAL'], /^\@[\w-]+/],
             // Matching xml tags
             [PR['PR_TAG'], /^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
             // Matching single or multiline xquery comments -> (: <text> :)
             [PR['PR_COMMENT'], /^\(:[\s\S]*?:\)/],
             // Tokenizing /{}:=;*,[]() as plain
             [PR['PR_PLAIN'], /^[\/\{\};,\[\]\(\)]$/],
             // Matching a double or single quoted, possibly multi-line, string.
             // with the special condition that a { in a string changes to xquery context 
             [PR['PR_STRING'], /^(?:\"(?:[^\"\\\{]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\\{]|\\[\s\S])*(?:\'|$))/, null, '"\''],
             // Matching standard xquery keywords
             [PR['PR_KEYWORD'], /^(?:xquery|where|version|variable|union|typeswitch|treat|to|then|text|stable|sortby|some|self|schema|satisfies|returns|return|ref|processing-instruction|preceding-sibling|preceding|precedes|parent|only|of|node|namespace|module|let|item|intersect|instance|in|import|if|function|for|follows|following-sibling|following|external|except|every|else|element|descending|descendant-or-self|descendant|define|default|declare|comment|child|cast|case|before|attribute|assert|ascending|as|ancestor-or-self|ancestor|after|eq|order|by|or|and|schema-element|document-node|node|at)\b/],
             // Matching standard xquery types
             [PR['PR_TYPE'], /^(?:xs:yearMonthDuration|xs:unsignedLong|xs:time|xs:string|xs:short|xs:QName|xs:Name|xs:long|xs:integer|xs:int|xs:gYearMonth|xs:gYear|xs:gMonthDay|xs:gDay|xs:float|xs:duration|xs:double|xs:decimal|xs:dayTimeDuration|xs:dateTime|xs:date|xs:byte|xs:boolean|xs:anyURI|xf:yearMonthDuration)\b/, null],
             // Matching standard xquery functions
             [PR_FUNCTION, /^(?:xp:dereference|xinc:node-expand|xinc:link-references|xinc:link-expand|xhtml:restructure|xhtml:clean|xhtml:add-lists|xdmp:zip-manifest|xdmp:zip-get|xdmp:zip-create|xdmp:xquery-version|xdmp:word-convert|xdmp:with-namespaces|xdmp:version|xdmp:value|xdmp:user-roles|xdmp:user-last-login|xdmp:user|xdmp:url-encode|xdmp:url-decode|xdmp:uri-is-file|xdmp:uri-format|xdmp:uri-content-type|xdmp:unquote|xdmp:unpath|xdmp:triggers-database|xdmp:trace|xdmp:to-json|xdmp:tidy|xdmp:subbinary|xdmp:strftime|xdmp:spawn-in|xdmp:spawn|xdmp:sleep|xdmp:shutdown|xdmp:set-session-field|xdmp:set-response-encoding|xdmp:set-response-content-type|xdmp:set-response-code|xdmp:set-request-time-limit|xdmp:set|xdmp:servers|xdmp:server-status|xdmp:server-name|xdmp:server|xdmp:security-database|xdmp:security-assert|xdmp:schema-database|xdmp:save|xdmp:role-roles|xdmp:role|xdmp:rethrow|xdmp:restart|xdmp:request-timestamp|xdmp:request-status|xdmp:request-cancel|xdmp:request|xdmp:redirect-response|xdmp:random|xdmp:quote|xdmp:query-trace|xdmp:query-meters|xdmp:product-edition|xdmp:privilege-roles|xdmp:privilege|xdmp:pretty-print|xdmp:powerpoint-convert|xdmp:platform|xdmp:permission|xdmp:pdf-convert|xdmp:path|xdmp:octal-to-integer|xdmp:node-uri|xdmp:node-replace|xdmp:node-kind|xdmp:node-insert-child|xdmp:node-insert-before|xdmp:node-insert-after|xdmp:node-delete|xdmp:node-database|xdmp:mul64|xdmp:modules-root|xdmp:modules-database|xdmp:merging|xdmp:merge-cancel|xdmp:merge|xdmp:md5|xdmp:logout|xdmp:login|xdmp:log-level|xdmp:log|xdmp:lock-release|xdmp:lock-acquire|xdmp:load|xdmp:invoke-in|xdmp:invoke|xdmp:integer-to-octal|xdmp:integer-to-hex|xdmp:http-put|xdmp:http-post|xdmp:http-options|xdmp:http-head|xdmp:http-get|xdmp:http-delete|xdmp:hosts|xdmp:host-status|xdmp:host-name|xdmp:host|xdmp:hex-to-integer|xdmp:hash64|xdmp:hash32|xdmp:has-privilege|xdmp:groups|xdmp:group-serves|xdmp:group-servers|xdmp:group-name|xdmp:group-hosts|xdmp:group|xdmp:get-session-field-names|xdmp:get-session-field|xdmp:get-response-encoding|xdmp:get-response-code|xdmp:get-request-username|xdmp:get-request-user|xdmp:get-request-url|xdmp:get-request-protocol|xdmp:get-request-path|xdmp:get-request-method|xdmp:get-request-header-names|xdmp:get-request-header|xdmp:get-request-field-names|xdmp:get-request-field-filename|xdmp:get-request-field-content-type|xdmp:get-request-field|xdmp:get-request-client-certificate|xdmp:get-request-client-address|xdmp:get-request-body|xdmp:get-current-user|xdmp:get-current-roles|xdmp:get|xdmp:function-name|xdmp:function-module|xdmp:function|xdmp:from-json|xdmp:forests|xdmp:forest-status|xdmp:forest-restore|xdmp:forest-restart|xdmp:forest-name|xdmp:forest-delete|xdmp:forest-databases|xdmp:forest-counts|xdmp:forest-clear|xdmp:forest-backup|xdmp:forest|xdmp:filesystem-file|xdmp:filesystem-directory|xdmp:exists|xdmp:excel-convert|xdmp:eval-in|xdmp:eval|xdmp:estimate|xdmp:email|xdmp:element-content-type|xdmp:elapsed-time|xdmp:document-set-quality|xdmp:document-set-property|xdmp:document-set-properties|xdmp:document-set-permissions|xdmp:document-set-collections|xdmp:document-remove-properties|xdmp:document-remove-permissions|xdmp:document-remove-collections|xdmp:document-properties|xdmp:document-locks|xdmp:document-load|xdmp:document-insert|xdmp:document-get-quality|xdmp:document-get-properties|xdmp:document-get-permissions|xdmp:document-get-collections|xdmp:document-get|xdmp:document-forest|xdmp:document-delete|xdmp:document-add-properties|xdmp:document-add-permissions|xdmp:document-add-collections|xdmp:directory-properties|xdmp:directory-locks|xdmp:directory-delete|xdmp:directory-create|xdmp:directory|xdmp:diacritic-less|xdmp:describe|xdmp:default-permissions|xdmp:default-collections|xdmp:databases|xdmp:database-restore-validate|xdmp:database-restore-status|xdmp:database-restore-cancel|xdmp:database-restore|xdmp:database-name|xdmp:database-forests|xdmp:database-backup-validate|xdmp:database-backup-status|xdmp:database-backup-purge|xdmp:database-backup-cancel|xdmp:database-backup|xdmp:database|xdmp:collection-properties|xdmp:collection-locks|xdmp:collection-delete|xdmp:collation-canonical-uri|xdmp:castable-as|xdmp:can-grant-roles|xdmp:base64-encode|xdmp:base64-decode|xdmp:architecture|xdmp:apply|xdmp:amp-roles|xdmp:amp|xdmp:add64|xdmp:add-response-header|xdmp:access|trgr:trigger-set-recursive|trgr:trigger-set-permissions|trgr:trigger-set-name|trgr:trigger-set-module|trgr:trigger-set-event|trgr:trigger-set-description|trgr:trigger-remove-permissions|trgr:trigger-module|trgr:trigger-get-permissions|trgr:trigger-enable|trgr:trigger-disable|trgr:trigger-database-online-event|trgr:trigger-data-event|trgr:trigger-add-permissions|trgr:remove-trigger|trgr:property-content|trgr:pre-commit|trgr:post-commit|trgr:get-trigger-by-id|trgr:get-trigger|trgr:document-scope|trgr:document-content|trgr:directory-scope|trgr:create-trigger|trgr:collection-scope|trgr:any-property-content|thsr:set-entry|thsr:remove-term|thsr:remove-synonym|thsr:remove-entry|thsr:query-lookup|thsr:lookup|thsr:load|thsr:insert|thsr:expand|thsr:add-synonym|spell:suggest-detailed|spell:suggest|spell:remove-word|spell:make-dictionary|spell:load|spell:levenshtein-distance|spell:is-correct|spell:insert|spell:double-metaphone|spell:add-word|sec:users-collection|sec:user-set-roles|sec:user-set-password|sec:user-set-name|sec:user-set-description|sec:user-set-default-permissions|sec:user-set-default-collections|sec:user-remove-roles|sec:user-privileges|sec:user-get-roles|sec:user-get-description|sec:user-get-default-permissions|sec:user-get-default-collections|sec:user-doc-permissions|sec:user-doc-collections|sec:user-add-roles|sec:unprotect-collection|sec:uid-for-name|sec:set-realm|sec:security-version|sec:security-namespace|sec:security-installed|sec:security-collection|sec:roles-collection|sec:role-set-roles|sec:role-set-name|sec:role-set-description|sec:role-set-default-permissions|sec:role-set-default-collections|sec:role-remove-roles|sec:role-privileges|sec:role-get-roles|sec:role-get-description|sec:role-get-default-permissions|sec:role-get-default-collections|sec:role-doc-permissions|sec:role-doc-collections|sec:role-add-roles|sec:remove-user|sec:remove-role-from-users|sec:remove-role-from-role|sec:remove-role-from-privileges|sec:remove-role-from-amps|sec:remove-role|sec:remove-privilege|sec:remove-amp|sec:protect-collection|sec:privileges-collection|sec:privilege-set-roles|sec:privilege-set-name|sec:privilege-remove-roles|sec:privilege-get-roles|sec:privilege-add-roles|sec:priv-doc-permissions|sec:priv-doc-collections|sec:get-user-names|sec:get-unique-elem-id|sec:get-role-names|sec:get-role-ids|sec:get-privilege|sec:get-distinct-permissions|sec:get-collection|sec:get-amp|sec:create-user-with-role|sec:create-user|sec:create-role|sec:create-privilege|sec:create-amp|sec:collections-collection|sec:collection-set-permissions|sec:collection-remove-permissions|sec:collection-get-permissions|sec:collection-add-permissions|sec:check-admin|sec:amps-collection|sec:amp-set-roles|sec:amp-remove-roles|sec:amp-get-roles|sec:amp-doc-permissions|sec:amp-doc-collections|sec:amp-add-roles|search:unparse|search:suggest|search:snippet|search:search|search:resolve-nodes|search:resolve|search:remove-constraint|search:parse|search:get-default-options|search:estimate|search:check-options|prof:value|prof:reset|prof:report|prof:invoke|prof:eval|prof:enable|prof:disable|prof:allowed|ppt:clean|pki:template-set-request|pki:template-set-name|pki:template-set-key-type|pki:template-set-key-options|pki:template-set-description|pki:template-in-use|pki:template-get-version|pki:template-get-request|pki:template-get-name|pki:template-get-key-type|pki:template-get-key-options|pki:template-get-id|pki:template-get-description|pki:need-certificate|pki:is-temporary|pki:insert-trusted-certificates|pki:insert-template|pki:insert-signed-certificates|pki:insert-certificate-revocation-list|pki:get-trusted-certificate-ids|pki:get-template-ids|pki:get-template-certificate-authority|pki:get-template-by-name|pki:get-template|pki:get-pending-certificate-requests-xml|pki:get-pending-certificate-requests-pem|pki:get-pending-certificate-request|pki:get-certificates-for-template-xml|pki:get-certificates-for-template|pki:get-certificates|pki:get-certificate-xml|pki:get-certificate-pem|pki:get-certificate|pki:generate-temporary-certificate-if-necessary|pki:generate-temporary-certificate|pki:generate-template-certificate-authority|pki:generate-certificate-request|pki:delete-template|pki:delete-certificate|pki:create-template|pdf:make-toc|pdf:insert-toc-headers|pdf:get-toc|pdf:clean|p:status-transition|p:state-transition|p:remove|p:pipelines|p:insert|p:get-by-id|p:get|p:execute|p:create|p:condition|p:collection|p:action|ooxml:runs-merge|ooxml:package-uris|ooxml:package-parts-insert|ooxml:package-parts|msword:clean|mcgm:polygon|mcgm:point|mcgm:geospatial-query-from-elements|mcgm:geospatial-query|mcgm:circle|math:tanh|math:tan|math:sqrt|math:sinh|math:sin|math:pow|math:modf|math:log10|math:log|math:ldexp|math:frexp|math:fmod|math:floor|math:fabs|math:exp|math:cosh|math:cos|math:ceil|math:atan2|math:atan|math:asin|math:acos|map:put|map:map|map:keys|map:get|map:delete|map:count|map:clear|lnk:to|lnk:remove|lnk:insert|lnk:get|lnk:from|lnk:create|kml:polygon|kml:point|kml:interior-polygon|kml:geospatial-query-from-elements|kml:geospatial-query|kml:circle|kml:box|gml:polygon|gml:point|gml:interior-polygon|gml:geospatial-query-from-elements|gml:geospatial-query|gml:circle|gml:box|georss:point|georss:geospatial-query|georss:circle|geo:polygon|geo:point|geo:interior-polygon|geo:geospatial-query-from-elements|geo:geospatial-query|geo:circle|geo:box|fn:zero-or-one|fn:years-from-duration|fn:year-from-dateTime|fn:year-from-date|fn:upper-case|fn:unordered|fn:true|fn:translate|fn:trace|fn:tokenize|fn:timezone-from-time|fn:timezone-from-dateTime|fn:timezone-from-date|fn:sum|fn:subtract-dateTimes-yielding-yearMonthDuration|fn:subtract-dateTimes-yielding-dayTimeDuration|fn:substring-before|fn:substring-after|fn:substring|fn:subsequence|fn:string-to-codepoints|fn:string-pad|fn:string-length|fn:string-join|fn:string|fn:static-base-uri|fn:starts-with|fn:seconds-from-time|fn:seconds-from-duration|fn:seconds-from-dateTime|fn:round-half-to-even|fn:round|fn:root|fn:reverse|fn:resolve-uri|fn:resolve-QName|fn:replace|fn:remove|fn:QName|fn:prefix-from-QName|fn:position|fn:one-or-more|fn:number|fn:not|fn:normalize-unicode|fn:normalize-space|fn:node-name|fn:node-kind|fn:nilled|fn:namespace-uri-from-QName|fn:namespace-uri-for-prefix|fn:namespace-uri|fn:name|fn:months-from-duration|fn:month-from-dateTime|fn:month-from-date|fn:minutes-from-time|fn:minutes-from-duration|fn:minutes-from-dateTime|fn:min|fn:max|fn:matches|fn:lower-case|fn:local-name-from-QName|fn:local-name|fn:last|fn:lang|fn:iri-to-uri|fn:insert-before|fn:index-of|fn:in-scope-prefixes|fn:implicit-timezone|fn:idref|fn:id|fn:hours-from-time|fn:hours-from-duration|fn:hours-from-dateTime|fn:floor|fn:false|fn:expanded-QName|fn:exists|fn:exactly-one|fn:escape-uri|fn:escape-html-uri|fn:error|fn:ends-with|fn:encode-for-uri|fn:empty|fn:document-uri|fn:doc-available|fn:doc|fn:distinct-values|fn:distinct-nodes|fn:default-collation|fn:deep-equal|fn:days-from-duration|fn:day-from-dateTime|fn:day-from-date|fn:data|fn:current-time|fn:current-dateTime|fn:current-date|fn:count|fn:contains|fn:concat|fn:compare|fn:collection|fn:codepoints-to-string|fn:codepoint-equal|fn:ceiling|fn:boolean|fn:base-uri|fn:avg|fn:adjust-time-to-timezone|fn:adjust-dateTime-to-timezone|fn:adjust-date-to-timezone|fn:abs|feed:unsubscribe|feed:subscription|feed:subscribe|feed:request|feed:item|feed:description|excel:clean|entity:enrich|dom:set-pipelines|dom:set-permissions|dom:set-name|dom:set-evaluation-context|dom:set-domain-scope|dom:set-description|dom:remove-pipeline|dom:remove-permissions|dom:remove|dom:get|dom:evaluation-context|dom:domains|dom:domain-scope|dom:create|dom:configuration-set-restart-user|dom:configuration-set-permissions|dom:configuration-set-evaluation-context|dom:configuration-set-default-domain|dom:configuration-get|dom:configuration-create|dom:collection|dom:add-pipeline|dom:add-permissions|dls:retention-rules|dls:retention-rule-remove|dls:retention-rule-insert|dls:retention-rule|dls:purge|dls:node-expand|dls:link-references|dls:link-expand|dls:documents-query|dls:document-versions-query|dls:document-version-uri|dls:document-version-query|dls:document-version-delete|dls:document-version-as-of|dls:document-version|dls:document-update|dls:document-unmanage|dls:document-set-quality|dls:document-set-property|dls:document-set-properties|dls:document-set-permissions|dls:document-set-collections|dls:document-retention-rules|dls:document-remove-properties|dls:document-remove-permissions|dls:document-remove-collections|dls:document-purge|dls:document-manage|dls:document-is-managed|dls:document-insert-and-manage|dls:document-include-query|dls:document-history|dls:document-get-permissions|dls:document-extract-part|dls:document-delete|dls:document-checkout-status|dls:document-checkout|dls:document-checkin|dls:document-add-properties|dls:document-add-permissions|dls:document-add-collections|dls:break-checkout|dls:author-query|dls:as-of-query|dbk:convert|dbg:wait|dbg:value|dbg:stopped|dbg:stop|dbg:step|dbg:status|dbg:stack|dbg:out|dbg:next|dbg:line|dbg:invoke|dbg:function|dbg:finish|dbg:expr|dbg:eval|dbg:disconnect|dbg:detach|dbg:continue|dbg:connect|dbg:clear|dbg:breakpoints|dbg:break|dbg:attached|dbg:attach|cvt:save-converted-documents|cvt:part-uri|cvt:destination-uri|cvt:basepath|cvt:basename|cts:words|cts:word-query-weight|cts:word-query-text|cts:word-query-options|cts:word-query|cts:word-match|cts:walk|cts:uris|cts:uri-match|cts:train|cts:tokenize|cts:thresholds|cts:stem|cts:similar-query-weight|cts:similar-query-nodes|cts:similar-query|cts:shortest-distance|cts:search|cts:score|cts:reverse-query-weight|cts:reverse-query-nodes|cts:reverse-query|cts:remainder|cts:registered-query-weight|cts:registered-query-options|cts:registered-query-ids|cts:registered-query|cts:register|cts:query|cts:quality|cts:properties-query-query|cts:properties-query|cts:polygon-vertices|cts:polygon|cts:point-longitude|cts:point-latitude|cts:point|cts:or-query-queries|cts:or-query|cts:not-query-weight|cts:not-query-query|cts:not-query|cts:near-query-weight|cts:near-query-queries|cts:near-query-options|cts:near-query-distance|cts:near-query|cts:highlight|cts:geospatial-co-occurrences|cts:frequency|cts:fitness|cts:field-words|cts:field-word-query-weight|cts:field-word-query-text|cts:field-word-query-options|cts:field-word-query-field-name|cts:field-word-query|cts:field-word-match|cts:entity-highlight|cts:element-words|cts:element-word-query-weight|cts:element-word-query-text|cts:element-word-query-options|cts:element-word-query-element-name|cts:element-word-query|cts:element-word-match|cts:element-values|cts:element-value-ranges|cts:element-value-query-weight|cts:element-value-query-text|cts:element-value-query-options|cts:element-value-query-element-name|cts:element-value-query|cts:element-value-match|cts:element-value-geospatial-co-occurrences|cts:element-value-co-occurrences|cts:element-range-query-weight|cts:element-range-query-value|cts:element-range-query-options|cts:element-range-query-operator|cts:element-range-query-element-name|cts:element-range-query|cts:element-query-query|cts:element-query-element-name|cts:element-query|cts:element-pair-geospatial-values|cts:element-pair-geospatial-value-match|cts:element-pair-geospatial-query-weight|cts:element-pair-geospatial-query-region|cts:element-pair-geospatial-query-options|cts:element-pair-geospatial-query-longitude-name|cts:element-pair-geospatial-query-latitude-name|cts:element-pair-geospatial-query-element-name|cts:element-pair-geospatial-query|cts:element-pair-geospatial-boxes|cts:element-geospatial-values|cts:element-geospatial-value-match|cts:element-geospatial-query-weight|cts:element-geospatial-query-region|cts:element-geospatial-query-options|cts:element-geospatial-query-element-name|cts:element-geospatial-query|cts:element-geospatial-boxes|cts:element-child-geospatial-values|cts:element-child-geospatial-value-match|cts:element-child-geospatial-query-weight|cts:element-child-geospatial-query-region|cts:element-child-geospatial-query-options|cts:element-child-geospatial-query-element-name|cts:element-child-geospatial-query-child-name|cts:element-child-geospatial-query|cts:element-child-geospatial-boxes|cts:element-attribute-words|cts:element-attribute-word-query-weight|cts:element-attribute-word-query-text|cts:element-attribute-word-query-options|cts:element-attribute-word-query-element-name|cts:element-attribute-word-query-attribute-name|cts:element-attribute-word-query|cts:element-attribute-word-match|cts:element-attribute-values|cts:element-attribute-value-ranges|cts:element-attribute-value-query-weight|cts:element-attribute-value-query-text|cts:element-attribute-value-query-options|cts:element-attribute-value-query-element-name|cts:element-attribute-value-query-attribute-name|cts:element-attribute-value-query|cts:element-attribute-value-match|cts:element-attribute-value-geospatial-co-occurrences|cts:element-attribute-value-co-occurrences|cts:element-attribute-range-query-weight|cts:element-attribute-range-query-value|cts:element-attribute-range-query-options|cts:element-attribute-range-query-operator|cts:element-attribute-range-query-element-name|cts:element-attribute-range-query-attribute-name|cts:element-attribute-range-query|cts:element-attribute-pair-geospatial-values|cts:element-attribute-pair-geospatial-value-match|cts:element-attribute-pair-geospatial-query-weight|cts:element-attribute-pair-geospatial-query-region|cts:element-attribute-pair-geospatial-query-options|cts:element-attribute-pair-geospatial-query-longitude-name|cts:element-attribute-pair-geospatial-query-latitude-name|cts:element-attribute-pair-geospatial-query-element-name|cts:element-attribute-pair-geospatial-query|cts:element-attribute-pair-geospatial-boxes|cts:document-query-uris|cts:document-query|cts:distance|cts:directory-query-uris|cts:directory-query-depth|cts:directory-query|cts:destination|cts:deregister|cts:contains|cts:confidence|cts:collections|cts:collection-query-uris|cts:collection-query|cts:collection-match|cts:classify|cts:circle-radius|cts:circle-center|cts:circle|cts:box-west|cts:box-south|cts:box-north|cts:box-east|cts:box|cts:bearing|cts:arc-intersection|cts:and-query-queries|cts:and-query-options|cts:and-query|cts:and-not-query-positive-query|cts:and-not-query-negative-query|cts:and-not-query|css:get|css:convert|cpf:success|cpf:failure|cpf:document-set-state|cpf:document-set-processing-status|cpf:document-set-last-updated|cpf:document-set-error|cpf:document-get-state|cpf:document-get-processing-status|cpf:document-get-last-updated|cpf:document-get-error|cpf:check-transition|alert:spawn-matching-actions|alert:rule-user-id-query|alert:rule-set-user-id|alert:rule-set-query|alert:rule-set-options|alert:rule-set-name|alert:rule-set-description|alert:rule-set-action|alert:rule-remove|alert:rule-name-query|alert:rule-insert|alert:rule-id-query|alert:rule-get-user-id|alert:rule-get-query|alert:rule-get-options|alert:rule-get-name|alert:rule-get-id|alert:rule-get-description|alert:rule-get-action|alert:rule-action-query|alert:remove-triggers|alert:make-rule|alert:make-log-action|alert:make-config|alert:make-action|alert:invoke-matching-actions|alert:get-my-rules|alert:get-all-rules|alert:get-actions|alert:find-matching-rules|alert:create-triggers|alert:config-set-uri|alert:config-set-trigger-ids|alert:config-set-options|alert:config-set-name|alert:config-set-description|alert:config-set-cpf-domain-names|alert:config-set-cpf-domain-ids|alert:config-insert|alert:config-get-uri|alert:config-get-trigger-ids|alert:config-get-options|alert:config-get-name|alert:config-get-id|alert:config-get-description|alert:config-get-cpf-domain-names|alert:config-get-cpf-domain-ids|alert:config-get|alert:config-delete|alert:action-set-options|alert:action-set-name|alert:action-set-module-root|alert:action-set-module-db|alert:action-set-module|alert:action-set-description|alert:action-remove|alert:action-insert|alert:action-get-options|alert:action-get-name|alert:action-get-module-root|alert:action-get-module-db|alert:action-get-module|alert:action-get-description|zero-or-one|years-from-duration|year-from-dateTime|year-from-date|upper-case|unordered|true|translate|trace|tokenize|timezone-from-time|timezone-from-dateTime|timezone-from-date|sum|subtract-dateTimes-yielding-yearMonthDuration|subtract-dateTimes-yielding-dayTimeDuration|substring-before|substring-after|substring|subsequence|string-to-codepoints|string-pad|string-length|string-join|string|static-base-uri|starts-with|seconds-from-time|seconds-from-duration|seconds-from-dateTime|round-half-to-even|round|root|reverse|resolve-uri|resolve-QName|replace|remove|QName|prefix-from-QName|position|one-or-more|number|not|normalize-unicode|normalize-space|node-name|node-kind|nilled|namespace-uri-from-QName|namespace-uri-for-prefix|namespace-uri|name|months-from-duration|month-from-dateTime|month-from-date|minutes-from-time|minutes-from-duration|minutes-from-dateTime|min|max|matches|lower-case|local-name-from-QName|local-name|last|lang|iri-to-uri|insert-before|index-of|in-scope-prefixes|implicit-timezone|idref|id|hours-from-time|hours-from-duration|hours-from-dateTime|floor|false|expanded-QName|exists|exactly-one|escape-uri|escape-html-uri|error|ends-with|encode-for-uri|empty|document-uri|doc-available|doc|distinct-values|distinct-nodes|default-collation|deep-equal|days-from-duration|day-from-dateTime|day-from-date|data|current-time|current-dateTime|current-date|count|contains|concat|compare|collection|codepoints-to-string|codepoint-equal|ceiling|boolean|base-uri|avg|adjust-time-to-timezone|adjust-dateTime-to-timezone|adjust-date-to-timezone|abs)\b/],
             // Matching normal words if none of the previous regular expressions matched
             [PR['PR_PLAIN'], /^[A-Za-z0-9_\-\:]+/],
             // Matching whitespaces
             [PR['PR_PLAIN'], /^[\t\n\r \xA0]+/]
             ]),
        ['xq', 'xquery']);
    �����������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-pascal.js��������������������������������������������������������������0000640�0001750�0001750�00000003052�12115200050�015701� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Contributed by peter dot kofler at code minus cop dot org
    
    /**
     * @fileoverview
     * Registers a language handler for (Turbo) Pascal.
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code in an HTML tag like
     *      <pre class="prettyprint lang-pascal">(my Pascal code)</pre>
     *
     * @author peter dot kofler at code minus cop dot org
     */
    
    PR.registerLangHandler(
        PR.createSimpleLexer(
            [ // shortcutStylePatterns
              // 'single-line-string'
              [PR.PR_STRING,        /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$))/, null, '\''],
              // Whitespace
              [PR.PR_PLAIN,         /^\s+/, null, ' \r\n\t\xA0']
            ],
            [ // fallthroughStylePatterns
              // A cStyleComments comment (* *) or {}
              [PR.PR_COMMENT,       /^\(\*[\s\S]*?(?:\*\)|$)|^\{[\s\S]*?(?:\}|$)/, null],
              [PR.PR_KEYWORD,       /^(?:ABSOLUTE|AND|ARRAY|ASM|ASSEMBLER|BEGIN|CASE|CONST|CONSTRUCTOR|DESTRUCTOR|DIV|DO|DOWNTO|ELSE|END|EXTERNAL|FOR|FORWARD|FUNCTION|GOTO|IF|IMPLEMENTATION|IN|INLINE|INTERFACE|INTERRUPT|LABEL|MOD|NOT|OBJECT|OF|OR|PACKED|PROCEDURE|PROGRAM|RECORD|REPEAT|SET|SHL|SHR|THEN|TO|TYPE|UNIT|UNTIL|USES|VAR|VIRTUAL|WHILE|WITH|XOR)\b/i, null],
              [PR.PR_LITERAL,       /^(?:true|false|self|nil)/i, null],
              [PR.PR_PLAIN,         /^[a-z][a-z0-9]*/i, null],
              // Literals .0, 0, 0.0 0E13
              [PR.PR_LITERAL,       /^(?:\$[a-f0-9]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?)/i,  null, '0123456789'],
              [PR.PR_PUNCTUATION,   /^.[^\s\w\.$@\'\/]*/, null]
            ]),
        ['pascal']);
    ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-matlab.js��������������������������������������������������������������0000640�0001750�0001750�00000062063�12115200050�015705� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013 by Amro <amroamroamro@gmail.com>
    //
    // Permission is hereby granted, free of charge, to any person obtaining a copy
    // of this software and associated documentation files (the "Software"), to deal
    // in the Software without restriction, including without limitation the rights
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    // copies of the Software, and to permit persons to whom the Software is
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in
    // all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    // THE SOFTWARE.
    
    /**
     * @fileoverview
     * Registers a language handler for MATLAB.
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code inside an HTML tag like
     *     <pre class="prettyprint lang-matlab">
     *     </pre>
     *
     * @see https://github.com/amroamroamro/prettify-matlab
     */
    (function (PR) {
      /*
        PR_PLAIN: plain text
        PR_STRING: string literals
        PR_KEYWORD: keywords
        PR_COMMENT: comments
        PR_TYPE: types
        PR_LITERAL: literal values (1, null, true, ..)
        PR_PUNCTUATION: punctuation string
        PR_SOURCE: embedded source
        PR_DECLARATION: markup declaration such as a DOCTYPE
        PR_TAG: sgml tag
        PR_ATTRIB_NAME: sgml attribute name
        PR_ATTRIB_VALUE: sgml attribute value
      */
      var PR_IDENTIFIER = "ident",
        PR_CONSTANT = "const",
        PR_FUNCTION = "fun",
        PR_FUNCTION_TOOLBOX = "fun_tbx",
        PR_SYSCMD = "syscmd",
        PR_CODE_OUTPUT = "codeoutput",
        PR_ERROR = "err",
        PR_WARNING = "wrn",
        PR_TRANSPOSE = "transpose",
        PR_LINE_CONTINUATION = "linecont";
    
      // Refer to: http://www.mathworks.com/help/matlab/functionlist-alpha.html
      var coreFunctions = [
        'abs|accumarray|acos(?:d|h)?|acot(?:d|h)?|acsc(?:d|h)?|actxcontrol(?:list|select)?|actxGetRunningServer|actxserver|addlistener|addpath|addpref|addtodate|airy|align|alim|all|allchild|alpha|alphamap|amd|ancestor|and|angle|annotation|any|area|arrayfun|asec(?:d|h)?|asin(?:d|h)?|assert|assignin|atan(?:2|d|h)?|audiodevinfo|audioplayer|audiorecorder|aufinfo|auread|autumn|auwrite|avifile|aviinfo|aviread|axes|axis|balance|bar(?:3|3h|h)?|base2dec|beep|BeginInvoke|bench|bessel(?:h|i|j|k|y)|beta|betainc|betaincinv|betaln|bicg|bicgstab|bicgstabl|bin2dec|bitand|bitcmp|bitget|bitmax|bitnot|bitor|bitset|bitshift|bitxor|blanks|blkdiag|bone|box|brighten|brush|bsxfun|builddocsearchdb|builtin|bvp4c|bvp5c|bvpget|bvpinit|bvpset|bvpxtend|calendar|calllib|callSoapService|camdolly|cameratoolbar|camlight|camlookat|camorbit|campan|campos|camproj|camroll|camtarget|camup|camva|camzoom|cart2pol|cart2sph|cast|cat|caxis|cd|cdf2rdf|cdfepoch|cdfinfo|cdflib(?:\.(?:close|closeVar|computeEpoch|computeEpoch16|create|createAttr|createVar|delete|deleteAttr|deleteAttrEntry|deleteAttrgEntry|deleteVar|deleteVarRecords|epoch16Breakdown|epochBreakdown|getAttrEntry|getAttrgEntry|getAttrMaxEntry|getAttrMaxgEntry|getAttrName|getAttrNum|getAttrScope|getCacheSize|getChecksum|getCompression|getCompressionCacheSize|getConstantNames|getConstantValue|getCopyright|getFileBackward|getFormat|getLibraryCopyright|getLibraryVersion|getMajority|getName|getNumAttrEntries|getNumAttrgEntries|getNumAttributes|getNumgAttributes|getReadOnlyMode|getStageCacheSize|getValidate|getVarAllocRecords|getVarBlockingFactor|getVarCacheSize|getVarCompression|getVarData|getVarMaxAllocRecNum|getVarMaxWrittenRecNum|getVarName|getVarNum|getVarNumRecsWritten|getVarPadValue|getVarRecordData|getVarReservePercent|getVarsMaxWrittenRecNum|getVarSparseRecords|getVersion|hyperGetVarData|hyperPutVarData|inquire|inquireAttr|inquireAttrEntry|inquireAttrgEntry|inquireVar|open|putAttrEntry|putAttrgEntry|putVarData|putVarRecordData|renameAttr|renameVar|setCacheSize|setChecksum|setCompression|setCompressionCacheSize|setFileBackward|setFormat|setMajority|setReadOnlyMode|setStageCacheSize|setValidate|setVarAllocBlockRecords|setVarBlockingFactor|setVarCacheSize|setVarCompression|setVarInitialRecs|setVarPadValue|SetVarReservePercent|setVarsCacheSize|setVarSparseRecords))?|cdfread|cdfwrite|ceil|cell2mat|cell2struct|celldisp|cellfun|cellplot|cellstr|cgs|checkcode|checkin|checkout|chol|cholinc|cholupdate|circshift|cla|clabel|class|clc|clear|clearvars|clf|clipboard|clock|close|closereq|cmopts|cmpermute|cmunique|colamd|colon|colorbar|colordef|colormap|colormapeditor|colperm|Combine|comet|comet3|commandhistory|commandwindow|compan|compass|complex|computer|cond|condeig|condest|coneplot|conj|containers\.Map|contour(?:3|c|f|slice)?|contrast|conv|conv2|convhull|convhulln|convn|cool|copper|copyfile|copyobj|corrcoef|cos(?:d|h)?|cot(?:d|h)?|cov|cplxpair|cputime|createClassFromWsdl|createSoapMessage|cross|csc(?:d|h)?|csvread|csvwrite|ctranspose|cumprod|cumsum|cumtrapz|curl|customverctrl|cylinder|daqread|daspect|datacursormode|datatipinfo|date|datenum|datestr|datetick|datevec|dbclear|dbcont|dbdown|dblquad|dbmex|dbquit|dbstack|dbstatus|dbstep|dbstop|dbtype|dbup|dde23|ddeget|ddesd|ddeset|deal|deblank|dec2base|dec2bin|dec2hex|decic|deconv|del2|delaunay|delaunay3|delaunayn|DelaunayTri|delete|demo|depdir|depfun|det|detrend|deval|diag|dialog|diary|diff|diffuse|dir|disp|display|dither|divergence|dlmread|dlmwrite|dmperm|doc|docsearch|dos|dot|dragrect|drawnow|dsearch|dsearchn|dynamicprops|echo|echodemo|edit|eig|eigs|ellipj|ellipke|ellipsoid|empty|enableNETfromNetworkDrive|enableservice|EndInvoke|enumeration|eomday|eq|erf|erfc|erfcinv|erfcx|erfinv|error|errorbar|errordlg|etime|etree|etreeplot|eval|evalc|evalin|event\.(?:EventData|listener|PropertyEvent|proplistener)|exifread|exist|exit|exp|expint|expm|expm1|export2wsdlg|eye|ezcontour|ezcontourf|ezmesh|ezmeshc|ezplot|ezplot3|ezpolar|ezsurf|ezsurfc|factor|factorial|fclose|feather|feature|feof|ferror|feval|fft|fft2|fftn|fftshift|fftw|fgetl|fgets|fieldnames|figure|figurepalette|fileattrib|filebrowser|filemarker|fileparts|fileread|filesep|fill|fill3|filter|filter2|find|findall|findfigs|findobj|findstr|finish|fitsdisp|fitsinfo|fitsread|fitswrite|fix|flag|flipdim|fliplr|flipud|floor|flow|fminbnd|fminsearch|fopen|format|fplot|fprintf|frame2im|fread|freqspace|frewind|fscanf|fseek|ftell|FTP|full|fullfile|func2str|functions|funm|fwrite|fzero|gallery|gamma|gammainc|gammaincinv|gammaln|gca|gcbf|gcbo|gcd|gcf|gco|ge|genpath|genvarname|get|getappdata|getenv|getfield|getframe|getpixelposition|getpref|ginput|gmres|gplot|grabcode|gradient|gray|graymon|grid|griddata(?:3|n)?|griddedInterpolant|gsvd|gt|gtext|guidata|guide|guihandles|gunzip|gzip|h5create|h5disp|h5info|h5read|h5readatt|h5write|h5writeatt|hadamard|handle|hankel|hdf|hdf5|hdf5info|hdf5read|hdf5write|hdfinfo|hdfread|hdftool|help|helpbrowser|helpdesk|helpdlg|helpwin|hess|hex2dec|hex2num|hgexport|hggroup|hgload|hgsave|hgsetget|hgtransform|hidden|hilb|hist|histc|hold|home|horzcat|hostid|hot|hsv|hsv2rgb|hypot|ichol|idivide|ifft|ifft2|ifftn|ifftshift|ilu|im2frame|im2java|imag|image|imagesc|imapprox|imfinfo|imformats|import|importdata|imread|imwrite|ind2rgb|ind2sub|inferiorto|info|inline|inmem|inpolygon|input|inputdlg|inputname|inputParser|inspect|instrcallback|instrfind|instrfindall|int2str|integral(?:2|3)?|interp(?:1|1q|2|3|ft|n)|interpstreamspeed|intersect|intmax|intmin|inv|invhilb|ipermute|isa|isappdata|iscell|iscellstr|ischar|iscolumn|isdir|isempty|isequal|isequaln|isequalwithequalnans|isfield|isfinite|isfloat|isglobal|ishandle|ishghandle|ishold|isinf|isinteger|isjava|iskeyword|isletter|islogical|ismac|ismatrix|ismember|ismethod|isnan|isnumeric|isobject|isocaps|isocolors|isonormals|isosurface|ispc|ispref|isprime|isprop|isreal|isrow|isscalar|issorted|isspace|issparse|isstr|isstrprop|isstruct|isstudent|isunix|isvarname|isvector|javaaddpath|javaArray|javachk|javaclasspath|javacomponent|javaMethod|javaMethodEDT|javaObject|javaObjectEDT|javarmpath|jet|keyboard|kron|lasterr|lasterror|lastwarn|lcm|ldivide|ldl|le|legend|legendre|length|libfunctions|libfunctionsview|libisloaded|libpointer|libstruct|license|light|lightangle|lighting|lin2mu|line|lines|linkaxes|linkdata|linkprop|linsolve|linspace|listdlg|listfonts|load|loadlibrary|loadobj|log|log10|log1p|log2|loglog|logm|logspace|lookfor|lower|ls|lscov|lsqnonneg|lsqr|lt|lu|luinc|magic|makehgtform|mat2cell|mat2str|material|matfile|matlab\.io\.MatFile|matlab\.mixin\.(?:Copyable|Heterogeneous(?:\.getDefaultScalarElement)?)|matlabrc|matlabroot|max|maxNumCompThreads|mean|median|membrane|memmapfile|memory|menu|mesh|meshc|meshgrid|meshz|meta\.(?:class(?:\.fromName)?|DynamicProperty|EnumeratedValue|event|MetaData|method|package(?:\.(?:fromName|getAllPackages))?|property)|metaclass|methods|methodsview|mex(?:\.getCompilerConfigurations)?|MException|mexext|mfilename|min|minres|minus|mislocked|mkdir|mkpp|mldivide|mlint|mlintrpt|mlock|mmfileinfo|mmreader|mod|mode|more|move|movefile|movegui|movie|movie2avi|mpower|mrdivide|msgbox|mtimes|mu2lin|multibandread|multibandwrite|munlock|namelengthmax|nargchk|narginchk|nargoutchk|native2unicode|nccreate|ncdisp|nchoosek|ncinfo|ncread|ncreadatt|ncwrite|ncwriteatt|ncwriteschema|ndgrid|ndims|ne|NET(?:\.(?:addAssembly|Assembly|convertArray|createArray|createGeneric|disableAutoRelease|enableAutoRelease|GenericClass|invokeGenericMethod|NetException|setStaticProperty))?|netcdf\.(?:abort|close|copyAtt|create|defDim|defGrp|defVar|defVarChunking|defVarDeflate|defVarFill|defVarFletcher32|delAtt|endDef|getAtt|getChunkCache|getConstant|getConstantNames|getVar|inq|inqAtt|inqAttID|inqAttName|inqDim|inqDimID|inqDimIDs|inqFormat|inqGrpName|inqGrpNameFull|inqGrpParent|inqGrps|inqLibVers|inqNcid|inqUnlimDims|inqVar|inqVarChunking|inqVarDeflate|inqVarFill|inqVarFletcher32|inqVarID|inqVarIDs|open|putAtt|putVar|reDef|renameAtt|renameDim|renameVar|setChunkCache|setDefaultFormat|setFill|sync)|newplot|nextpow2|nnz|noanimate|nonzeros|norm|normest|not|notebook|now|nthroot|null|num2cell|num2hex|num2str|numel|nzmax|ode(?:113|15i|15s|23|23s|23t|23tb|45)|odeget|odeset|odextend|onCleanup|ones|open|openfig|opengl|openvar|optimget|optimset|or|ordeig|orderfields|ordqz|ordschur|orient|orth|pack|padecoef|pagesetupdlg|pan|pareto|parseSoapResponse|pascal|patch|path|path2rc|pathsep|pathtool|pause|pbaspect|pcg|pchip|pcode|pcolor|pdepe|pdeval|peaks|perl|perms|permute|pie|pink|pinv|planerot|playshow|plot|plot3|plotbrowser|plotedit|plotmatrix|plottools|plotyy|plus|pol2cart|polar|poly|polyarea|polyder|polyeig|polyfit|polyint|polyval|polyvalm|pow2|power|ppval|prefdir|preferences|primes|print|printdlg|printopt|printpreview|prod|profile|profsave|propedit|propertyeditor|psi|publish|PutCharArray|PutFullMatrix|PutWorkspaceData|pwd|qhull|qmr|qr|qrdelete|qrinsert|qrupdate|quad|quad2d|quadgk|quadl|quadv|questdlg|quit|quiver|quiver3|qz|rand|randi|randn|randperm|RandStream(?:\.(?:create|getDefaultStream|getGlobalStream|list|setDefaultStream|setGlobalStream))?|rank|rat|rats|rbbox|rcond|rdivide|readasync|real|reallog|realmax|realmin|realpow|realsqrt|record|rectangle|rectint|recycle|reducepatch|reducevolume|refresh|refreshdata|regexp|regexpi|regexprep|regexptranslate|rehash|rem|Remove|RemoveAll|repmat|reset|reshape|residue|restoredefaultpath|rethrow|rgb2hsv|rgb2ind|rgbplot|ribbon|rmappdata|rmdir|rmfield|rmpath|rmpref|rng|roots|rose|rosser|rot90|rotate|rotate3d|round|rref|rsf2csf|run|save|saveas|saveobj|savepath|scatter|scatter3|schur|sec|secd|sech|selectmoveresize|semilogx|semilogy|sendmail|serial|set|setappdata|setdiff|setenv|setfield|setpixelposition|setpref|setstr|setxor|shading|shg|shiftdim|showplottool|shrinkfaces|sign|sin(?:d|h)?|size|slice|smooth3|snapnow|sort|sortrows|sound|soundsc|spalloc|spaugment|spconvert|spdiags|specular|speye|spfun|sph2cart|sphere|spinmap|spline|spones|spparms|sprand|sprandn|sprandsym|sprank|spring|sprintf|spy|sqrt|sqrtm|squeeze|ss2tf|sscanf|stairs|startup|std|stem|stem3|stopasync|str2double|str2func|str2mat|str2num|strcat|strcmp|strcmpi|stream2|stream3|streamline|streamparticles|streamribbon|streamslice|streamtube|strfind|strjust|strmatch|strncmp|strncmpi|strread|strrep|strtok|strtrim|struct2cell|structfun|strvcat|sub2ind|subplot|subsasgn|subsindex|subspace|subsref|substruct|subvolume|sum|summer|superclasses|superiorto|support|surf|surf2patch|surface|surfc|surfl|surfnorm|svd|svds|swapbytes|symamd|symbfact|symmlq|symrcm|symvar|system|tan(?:d|h)?|tar|tempdir|tempname|tetramesh|texlabel|text|textread|textscan|textwrap|tfqmr|throw|tic|Tiff(?:\.(?:getTagNames|getVersion))?|timer|timerfind|timerfindall|times|timeseries|title|toc|todatenum|toeplitz|toolboxdir|trace|transpose|trapz|treelayout|treeplot|tril|trimesh|triplequad|triplot|TriRep|TriScatteredInterp|trisurf|triu|tscollection|tsearch|tsearchn|tstool|type|typecast|uibuttongroup|uicontextmenu|uicontrol|uigetdir|uigetfile|uigetpref|uiimport|uimenu|uiopen|uipanel|uipushtool|uiputfile|uiresume|uisave|uisetcolor|uisetfont|uisetpref|uistack|uitable|uitoggletool|uitoolbar|uiwait|uminus|undocheckout|unicode2native|union|unique|unix|unloadlibrary|unmesh|unmkpp|untar|unwrap|unzip|uplus|upper|urlread|urlwrite|usejava|userpath|validateattributes|validatestring|vander|var|vectorize|ver|verctrl|verLessThan|version|vertcat|VideoReader(?:\.isPlatformSupported)?|VideoWriter(?:\.getProfiles)?|view|viewmtx|visdiff|volumebounds|voronoi|voronoin|wait|waitbar|waitfor|waitforbuttonpress|warndlg|warning|waterfall|wavfinfo|wavplay|wavread|wavrecord|wavwrite|web|weekday|what|whatsnew|which|whitebg|who|whos|wilkinson|winopen|winqueryreg|winter|wk1finfo|wk1read|wk1write|workspace|xlabel|xlim|xlsfinfo|xlsread|xlswrite|xmlread|xmlwrite|xor|xslt|ylabel|ylim|zeros|zip|zlabel|zlim|zoom'
      ].join("|");
      var statsFunctions = [
        'addedvarplot|andrewsplot|anova(?:1|2|n)|ansaribradley|aoctool|barttest|bbdesign|beta(?:cdf|fit|inv|like|pdf|rnd|stat)|bino(?:cdf|fit|inv|pdf|rnd|stat)|biplot|bootci|bootstrp|boxplot|candexch|candgen|canoncorr|capability|capaplot|caseread|casewrite|categorical|ccdesign|cdfplot|chi2(?:cdf|gof|inv|pdf|rnd|stat)|cholcov|Classification(?:BaggedEnsemble|Discriminant(?:\.(?:fit|make|template))?|Ensemble|KNN(?:\.(?:fit|template))?|PartitionedEnsemble|PartitionedModel|Tree(?:\.(?:fit|template))?)|classify|classregtree|cluster|clusterdata|cmdscale|combnk|Compact(?:Classification(?:Discriminant|Ensemble|Tree)|Regression(?:Ensemble|Tree)|TreeBagger)|confusionmat|controlchart|controlrules|cophenet|copula(?:cdf|fit|param|pdf|rnd|stat)|cordexch|corr|corrcov|coxphfit|createns|crosstab|crossval|cvpartition|datasample|dataset|daugment|dcovary|dendrogram|dfittool|disttool|dummyvar|dwtest|ecdf|ecdfhist|ev(?:cdf|fit|inv|like|pdf|rnd|stat)|ExhaustiveSearcher|exp(?:cdf|fit|inv|like|pdf|rnd|stat)|factoran|fcdf|ff2n|finv|fitdist|fitensemble|fpdf|fracfact|fracfactgen|friedman|frnd|fstat|fsurfht|fullfact|gagerr|gam(?:cdf|fit|inv|like|pdf|rnd|stat)|GeneralizedLinearModel(?:\.fit)?|geo(?:cdf|inv|mean|pdf|rnd|stat)|gev(?:cdf|fit|inv|like|pdf|rnd|stat)|gline|glmfit|glmval|glyphplot|gmdistribution(?:\.fit)?|gname|gp(?:cdf|fit|inv|like|pdf|rnd|stat)|gplotmatrix|grp2idx|grpstats|gscatter|haltonset|harmmean|hist3|histfit|hmm(?:decode|estimate|generate|train|viterbi)|hougen|hyge(?:cdf|inv|pdf|rnd|stat)|icdf|inconsistent|interactionplot|invpred|iqr|iwishrnd|jackknife|jbtest|johnsrnd|KDTreeSearcher|kmeans|knnsearch|kruskalwallis|ksdensity|kstest|kstest2|kurtosis|lasso|lassoglm|lassoPlot|leverage|lhsdesign|lhsnorm|lillietest|LinearModel(?:\.fit)?|linhyptest|linkage|logn(?:cdf|fit|inv|like|pdf|rnd|stat)|lsline|mad|mahal|maineffectsplot|manova1|manovacluster|mdscale|mhsample|mle|mlecov|mnpdf|mnrfit|mnrnd|mnrval|moment|multcompare|multivarichart|mvn(?:cdf|pdf|rnd)|mvregress|mvregresslike|mvt(?:cdf|pdf|rnd)|NaiveBayes(?:\.fit)?|nan(?:cov|max|mean|median|min|std|sum|var)|nbin(?:cdf|fit|inv|pdf|rnd|stat)|ncf(?:cdf|inv|pdf|rnd|stat)|nct(?:cdf|inv|pdf|rnd|stat)|ncx2(?:cdf|inv|pdf|rnd|stat)|NeighborSearcher|nlinfit|nlintool|nlmefit|nlmefitsa|nlparci|nlpredci|nnmf|nominal|NonLinearModel(?:\.fit)?|norm(?:cdf|fit|inv|like|pdf|rnd|stat)|normplot|normspec|ordinal|outlierMeasure|parallelcoords|paretotails|partialcorr|pcacov|pcares|pdf|pdist|pdist2|pearsrnd|perfcurve|perms|piecewisedistribution|plsregress|poiss(?:cdf|fit|inv|pdf|rnd|tat)|polyconf|polytool|prctile|princomp|ProbDist(?:Kernel|Parametric|UnivKernel|UnivParam)?|probplot|procrustes|qqplot|qrandset|qrandstream|quantile|randg|random|randsample|randtool|range|rangesearch|ranksum|rayl(?:cdf|fit|inv|pdf|rnd|stat)|rcoplot|refcurve|refline|regress|Regression(?:BaggedEnsemble|Ensemble|PartitionedEnsemble|PartitionedModel|Tree(?:\.(?:fit|template))?)|regstats|relieff|ridge|robustdemo|robustfit|rotatefactors|rowexch|rsmdemo|rstool|runstest|sampsizepwr|scatterhist|sequentialfs|signrank|signtest|silhouette|skewness|slicesample|sobolset|squareform|statget|statset|stepwise|stepwisefit|surfht|tabulate|tblread|tblwrite|tcdf|tdfread|tiedrank|tinv|tpdf|TreeBagger|treedisp|treefit|treeprune|treetest|treeval|trimmean|trnd|tstat|ttest|ttest2|unid(?:cdf|inv|pdf|rnd|stat)|unif(?:cdf|inv|it|pdf|rnd|stat)|vartest(?:2|n)?|wbl(?:cdf|fit|inv|like|pdf|rnd|stat)|wblplot|wishrnd|x2fx|xptread|zscore|ztest'
      ].join("|");
      var imageFunctions = [
        'adapthisteq|analyze75info|analyze75read|applycform|applylut|axes2pix|bestblk|blockproc|bwarea|bwareaopen|bwboundaries|bwconncomp|bwconvhull|bwdist|bwdistgeodesic|bweuler|bwhitmiss|bwlabel|bwlabeln|bwmorph|bwpack|bwperim|bwselect|bwtraceboundary|bwulterode|bwunpack|checkerboard|col2im|colfilt|conndef|convmtx2|corner|cornermetric|corr2|cp2tform|cpcorr|cpselect|cpstruct2pairs|dct2|dctmtx|deconvblind|deconvlucy|deconvreg|deconvwnr|decorrstretch|demosaic|dicom(?:anon|dict|info|lookup|read|uid|write)|edge|edgetaper|entropy|entropyfilt|fan2para|fanbeam|findbounds|fliptform|freqz2|fsamp2|fspecial|ftrans2|fwind1|fwind2|getheight|getimage|getimagemodel|getline|getneighbors|getnhood|getpts|getrangefromclass|getrect|getsequence|gray2ind|graycomatrix|graycoprops|graydist|grayslice|graythresh|hdrread|hdrwrite|histeq|hough|houghlines|houghpeaks|iccfind|iccread|iccroot|iccwrite|idct2|ifanbeam|im2bw|im2col|im2double|im2int16|im2java2d|im2single|im2uint16|im2uint8|imabsdiff|imadd|imadjust|ImageAdapter|imageinfo|imagemodel|imapplymatrix|imattributes|imbothat|imclearborder|imclose|imcolormaptool|imcomplement|imcontour|imcontrast|imcrop|imdilate|imdisplayrange|imdistline|imdivide|imellipse|imerode|imextendedmax|imextendedmin|imfill|imfilter|imfindcircles|imfreehand|imfuse|imgca|imgcf|imgetfile|imhandles|imhist|imhmax|imhmin|imimposemin|imlincomb|imline|immagbox|immovie|immultiply|imnoise|imopen|imoverview|imoverviewpanel|impixel|impixelinfo|impixelinfoval|impixelregion|impixelregionpanel|implay|impoint|impoly|impositionrect|improfile|imputfile|impyramid|imreconstruct|imrect|imregconfig|imregionalmax|imregionalmin|imregister|imresize|imroi|imrotate|imsave|imscrollpanel|imshow|imshowpair|imsubtract|imtool|imtophat|imtransform|imview|ind2gray|ind2rgb|interfileinfo|interfileread|intlut|ippl|iptaddcallback|iptcheckconn|iptcheckhandle|iptcheckinput|iptcheckmap|iptchecknargin|iptcheckstrs|iptdemos|iptgetapi|iptGetPointerBehavior|iptgetpref|ipticondir|iptnum2ordinal|iptPointerManager|iptprefs|iptremovecallback|iptSetPointerBehavior|iptsetpref|iptwindowalign|iradon|isbw|isflat|isgray|isicc|isind|isnitf|isrgb|isrset|lab2double|lab2uint16|lab2uint8|label2rgb|labelmatrix|makecform|makeConstrainToRectFcn|makehdr|makelut|makeresampler|maketform|mat2gray|mean2|medfilt2|montage|nitfinfo|nitfread|nlfilter|normxcorr2|ntsc2rgb|openrset|ordfilt2|otf2psf|padarray|para2fan|phantom|poly2mask|psf2otf|qtdecomp|qtgetblk|qtsetblk|radon|rangefilt|reflect|regionprops|registration\.metric\.(?:MattesMutualInformation|MeanSquares)|registration\.optimizer\.(?:OnePlusOneEvolutionary|RegularStepGradientDescent)|rgb2gray|rgb2ntsc|rgb2ycbcr|roicolor|roifill|roifilt2|roipoly|rsetwrite|std2|stdfilt|strel|stretchlim|subimage|tformarray|tformfwd|tforminv|tonemap|translate|truesize|uintlut|viscircles|warp|watershed|whitepoint|wiener2|xyz2double|xyz2uint16|ycbcr2rgb'
      ].join("|");
      var optimFunctions = [
        'bintprog|color|fgoalattain|fminbnd|fmincon|fminimax|fminsearch|fminunc|fseminf|fsolve|fzero|fzmult|gangstr|ktrlink|linprog|lsqcurvefit|lsqlin|lsqnonlin|lsqnonneg|optimget|optimset|optimtool|quadprog'
      ].join("|");
    
      // identifiers: variable/function name, or a chain of variable names joined by dots (obj.method, struct.field1.field2, etc..)
      // valid variable names (start with letter, and contains letters, digits, and underscores).
      // we match "xx.yy" as a whole so that if "xx" is plain and "yy" is not, we dont get a false positive for "yy"
      //var reIdent = '(?:[a-zA-Z][a-zA-Z0-9_]*)';
      //var reIdentChain = '(?:' + reIdent + '(?:\.' + reIdent + ')*' + ')';
    
      // patterns that always start with a known character. Must have a shortcut string.
      var shortcutStylePatterns = [
        // whitespaces: space, tab, carriage return, line feed, line tab, form-feed, non-break space
        [PR.PR_PLAIN, /^[ \t\r\n\v\f\xA0]+/, null, " \t\r\n\u000b\u000c\u00a0"],
    
        // block comments
        //TODO: chokes on nested block comments
        //TODO: false positives when the lines with %{ and %} contain non-spaces
        //[PR.PR_COMMENT, /^%(?:[^\{].*|\{(?:%|%*[^\}%])*(?:\}+%?)?)/, null],
        [PR.PR_COMMENT, /^%\{[^%]*%+(?:[^\}%][^%]*%+)*\}/, null],
    
        // single-line comments
        [PR.PR_COMMENT, /^%[^\r\n]*/, null, "%"],
    
        // system commands
        [PR_SYSCMD, /^![^\r\n]*/, null, "!"]
      ];
    
      // patterns that will be tried in order if the shortcut ones fail. May have shortcuts.
      var fallthroughStylePatterns = [
        // line continuation
        [PR_LINE_CONTINUATION, /^\.\.\.\s*[\r\n]/, null],
    
        // error message
        [PR_ERROR, /^\?\?\? [^\r\n]*/, null],
    
        // warning message
        [PR_WARNING, /^Warning: [^\r\n]*/, null],
    
        // command prompt/output
        //[PR_CODE_OUTPUT, /^>>\s+[^\r\n]*[\r\n]{1,2}[^=]*=[^\r\n]*[\r\n]{1,2}[^\r\n]*/, null],    // full command output (both loose/compact format): `>> EXP\nVAR =\n VAL`
        [PR_CODE_OUTPUT, /^>>\s+/, null],      // only the command prompt `>> `
        [PR_CODE_OUTPUT, /^octave:\d+>\s+/, null],  // Octave command prompt `octave:1> `
    
        // identifier (chain) or closing-parenthesis/brace/bracket, and IS followed by transpose operator
        // this way we dont misdetect the transpose operator ' as the start of a string
        ["lang-matlab-operators", /^((?:[a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)*|\)|\]|\}|\.)')/, null],
    
        // identifier (chain), and NOT followed by transpose operator
        // this must come AFTER the "is followed by transpose" step (otherwise it chops the last char of identifier)
        ["lang-matlab-identifiers", /^([a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)*)(?!')/, null],
    
        // single-quoted strings: allow for escaping with '', no multilines
        //[PR.PR_STRING, /(?:(?<=(?:\(|\[|\{|\s|=|;|,|:))|^)'(?:[^']|'')*'(?=(?:\)|\]|\}|\s|=|;|,|:|~|<|>|&|-|\+|\*|\.|\^|\|))/, null],  // string vs. transpose (check before/after context using negative/positive lookbehind/lookahead)
        [PR.PR_STRING, /^'(?:[^']|'')*'/, null],  // "'"
    
        // floating point numbers: 1, 1.0, 1i, -1.1E-1
        [PR.PR_LITERAL, /^[+\-]?\.?\d+(?:\.\d*)?(?:[Ee][+\-]?\d+)?[ij]?/, null],
    
        // parentheses, braces, brackets
        [PR.PR_TAG, /^(?:\{|\}|\(|\)|\[|\])/, null],  // "{}()[]"
    
        // other operators
        [PR.PR_PUNCTUATION, /^(?:<|>|=|~|@|&|;|,|:|!|\-|\+|\*|\^|\.|\||\\|\/)/, null]
      ];
    
      var identifiersPatterns = [
        // list of keywords (`iskeyword`)
        [PR.PR_KEYWORD, /^\b(?:break|case|catch|classdef|continue|else|elseif|end|for|function|global|if|otherwise|parfor|persistent|return|spmd|switch|try|while)\b/, null],
    
        // some specials variables/constants
        [PR_CONSTANT, /^\b(?:true|false|inf|Inf|nan|NaN|eps|pi|ans|nargin|nargout|varargin|varargout)\b/, null],
    
        // some data types
        [PR.PR_TYPE, /^\b(?:cell|struct|char|double|single|logical|u?int(?:8|16|32|64)|sparse)\b/, null],
    
        // commonly used builtin functions from core MATLAB and a few popular toolboxes
        [PR_FUNCTION, new RegExp('^\\b(?:' + coreFunctions + ')\\b'), null],
        [PR_FUNCTION_TOOLBOX, new RegExp('^\\b(?:' + statsFunctions + ')\\b'), null],
        [PR_FUNCTION_TOOLBOX, new RegExp('^\\b(?:' + imageFunctions + ')\\b'), null],
        [PR_FUNCTION_TOOLBOX, new RegExp('^\\b(?:' + optimFunctions + ')\\b'), null],
    
        // plain identifier (user-defined variable/function name)
        [PR_IDENTIFIER, /^[a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)*/, null]
      ];
    
      var operatorsPatterns = [
        // forward to identifiers to match
        ["lang-matlab-identifiers", /^([a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)*)/, null],
    
        // parentheses, braces, brackets
        [PR.PR_TAG, /^(?:\{|\}|\(|\)|\[|\])/, null],  // "{}()[]"
    
        // other operators
        [PR.PR_PUNCTUATION, /^(?:<|>|=|~|@|&|;|,|:|!|\-|\+|\*|\^|\.|\||\\|\/)/, null],
    
        // transpose operators
        [PR_TRANSPOSE, /^'/, null]
      ];
    
      PR.registerLangHandler(
        PR.createSimpleLexer([], identifiersPatterns),
        ["matlab-identifiers"]
      );
      PR.registerLangHandler(
        PR.createSimpleLexer([], operatorsPatterns),
        ["matlab-operators"]
      );
      PR.registerLangHandler(
        PR.createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns),
        ["matlab"]
      );
    })(window['PR']);
    �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-wiki.js����������������������������������������������������������������0000640�0001750�0001750�00000003567�12115200050�015414� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2009 Google Inc.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    /**
     * @fileoverview
     * Registers a language handler for Wiki pages.
     *
     * Based on WikiSyntax at http://code.google.com/p/support/wiki/WikiSyntax
     *
     * @author mikesamuel@gmail.com
     */
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             // Whitespace
             [PR['PR_PLAIN'],       /^[\t \xA0a-gi-z0-9]+/, null,
              '\t \xA0abcdefgijklmnopqrstuvwxyz0123456789'],
             // Wiki formatting
             [PR['PR_PUNCTUATION'], /^[=*~\^\[\]]+/, null, '=*~^[]']
            ],
            [
             // Meta-info like #summary, #labels, etc.
             ['lang-wiki.meta',  /(?:^^|\r\n?|\n)(#[a-z]+)\b/],
             // A WikiWord
             [PR['PR_LITERAL'],     /^(?:[A-Z][a-z][a-z0-9]+[A-Z][a-z][a-zA-Z0-9]+)\b/
              ],
             // A preformatted block in an unknown language
             ['lang-',           /^\{\{\{([\s\S]+?)\}\}\}/],
             // A block of source code in an unknown language
             ['lang-',           /^`([^\r\n`]+)`/],
             // An inline URL.
             [PR['PR_STRING'],
              /^https?:\/\/[^\/?#\s]*(?:\/[^?#\s]*)?(?:\?[^#\s]*)?(?:#\S*)?/i],
             [PR['PR_PLAIN'],       /^(?:\r\n|[\s\S])[^#=*~^A-Zh\{`\[\r\n]*/]
            ]),
        ['wiki']);
    
    PR['registerLangHandler'](
        PR['createSimpleLexer']([[PR['PR_KEYWORD'], /^#[a-z]+/i, null, '#']], []),
        ['wiki.meta']);
    �����������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/src/lang-tcl.js�����������������������������������������������������������������0000640�0001750�0001750�00000005062�12115200050�015223� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2012 Pyrios.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    
    /**
     * @fileoverview
     * Registers a language handler for TCL
     *
     *
     * To use, include prettify.js and this file in your HTML page.
     * Then put your code in an HTML tag like
     *      <pre class="prettyprint lang-tcl">proc foo {} {puts bar}</pre>
     *
     * I copy-pasted lang-lisp.js, so this is probably not 100% accurate.
     * I used http://wiki.tcl.tk/1019 for the keywords, but tried to only
     * include as keywords that had more impact on the program flow
     * rather than providing convenience. For example, I included 'if'
     * since that provides branching, but left off 'open' since that is more
     * like a proc. Add more if it makes sense.
     *
     * @author pyrios@gmail.com
     */
    
    PR['registerLangHandler'](
        PR['createSimpleLexer'](
            [
             ['opn',             /^\{+/, null, '{'],
             ['clo',             /^\}+/, null, '}'],
             // A line comment that starts with ;
             [PR['PR_COMMENT'],     /^#[^\r\n]*/, null, '#'],
             // Whitespace
             [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
             // A double quoted, possibly multi-line, string.
             [PR['PR_STRING'],      /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"']
            ],
            [
             [PR['PR_KEYWORD'],     /^(?:after|append|apply|array|break|case|catch|continue|error|eval|exec|exit|expr|for|foreach|if|incr|info|proc|return|set|switch|trace|uplevel|upvar|while)\b/, null],
             [PR['PR_LITERAL'],
              /^[+\-]?(?:[0#]x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i],
             // A single quote possibly followed by a word that optionally ends with
             // = ! or ?.
             [PR['PR_LITERAL'],
              /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],
             // A word that optionally ends with = ! or ?.
             [PR['PR_PLAIN'],
              /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],
             // A printable non-space non-special character
             [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/]
            ]),
        ['tcl']);
    ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/�������������������������������������������������������������������������0000751�0001750�0001750�00000000000�12362767251�013746� 5����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/index.html���������������������������������������������������������������0000640�0001750�0001750�00000006116�12115200050�015716� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
    <html><head>
    <title>Prettify Themes Gallery</title>
    <style type="text/css">
    iframe { width: 100%; border-style: none; margin: 0; padding: 0 }
    </style>
    <script>
    var allThemes = [
      { name: 'default' },
      { name: 'desert',
        authorHtml: '<a href="http://code.google.com/u/@VhJeSlJYBhVMWgF7/">'
            + 'techto&hellip;@<\/a>' },
      { name: 'sunburst', authorHtml: 'David Leibovic' },
      { name: 'sons-of-obsidian',
        authorHtml: '<a href="http://CodeTunnel.com/blog/post/71'
            + '/google-code-prettify-obsidian-theme">Alex Ford<\/a>' },
      { name: 'doxy', authorHtml: 'Robert Sperberg' },
    ];
    
    // Called by the demo.html frames loaded per theme to
    // size the iframes properly and to allow them to tile
    // the page nicely.
    function adjustChildIframeSize(themeName, width, height) {
      if (typeof console != 'undefined') {
        try {
          console.log('adjusting ' + themeName + ' to ' + width + 'x' + height);
        } catch (ex) {
          // Don't bother logging log failure.
        }
      }
    
      var container = document.getElementById(themeName).parentNode;
      container.style.width = (+width + 16) + 'px';
      container.style.display = 'inline-block';
      var iframe = container.getElementsByTagName('iframe')[0];
      iframe.style.height = (+height + 16) + 'px';
    }
    </script>
    </head>
    
    <body>
    <noscript>This page requires JavaScript</noscript>
    
    <h1>Gallery of themes for
    <a href="http://code.google.com/p/google-code-prettify/">code prettify</a></h1>
    <p>
    Click on a theme name for a link to the file in revision control.
    Print preview this page to see how the themes work on the printed page.
    </p>
    <script>(function () {
      // Produce an iframe per theme.
      // We pass the threme name to the iframe via its URI query, and
      // it loads prettify and the theme CSS, and calls back to this page
      // to resize the iframe.
      for (var i = 0, n = allThemes.length; i < n; ++i) {
        var theme = allThemes[i];
        if (!theme) { continue; }
        var iframe = document.createElement('iframe');
        iframe.name = theme.name;
        iframe.src = 'demo.html?' + encodeURIComponent(theme.name);
        var header = document.createElement('h2');
        header.id = theme.name;
        var linkToThemeSrc = document.createElement('a');
        linkToThemeSrc.href = (
            'http://code.google.com/p/google-code-prettify/source/browse/trunk/' +
            (theme.name === 'default'
             ? 'src/prettify.css'
             : 'styles/' + encodeURIComponent(theme.name) + '.css'));
        linkToThemeSrc.appendChild(document.createTextNode(
           theme.name.replace(/\b[a-z]/g,  // Capitalize first letter of each word
           function (letter) { return letter.toUpperCase(); })));
        header.appendChild(linkToThemeSrc);
    
        var attribution;
        if (theme.authorHtml) {
          attribution = document.createElement('span');
          attribution.className = 'attribution';
          attribution.innerHTML = 'by ' + theme.authorHtml;
        }
    
        var div = document.createElement('div');
        div.appendChild(header);
        if (attribution) { div.appendChild(attribution); }
        div.appendChild(iframe);
        document.body.appendChild(div);
      }
    })()</script>
    
    </body></html>
    ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/sons-of-obsidian.css�����������������������������������������������������0000640�0001750�0001750�00000002757�12115200050�017614� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/*
     * Derived from einaros's Sons of Obsidian theme at
     * http://studiostyl.es/schemes/son-of-obsidian by
     * Alex Ford of CodeTunnel:
     * http://CodeTunnel.com/blog/post/71/google-code-prettify-obsidian-theme
     */
    
    .str
    {
        color: #EC7600;
    }
    .kwd
    {
        color: #93C763;
    }
    .com
    {
        color: #66747B;
    }
    .typ
    {
        color: #678CB1;
    }
    .lit
    {
        color: #FACD22;
    }
    .pun
    {
        color: #F1F2F3;
    }
    .pln
    {
        color: #F1F2F3;
    }
    .tag
    {
        color: #8AC763;
    }
    .atn
    {
        color: #E0E2E4;
    }
    .atv
    {
        color: #EC7600;
    }
    .dec
    {
        color: purple;
    }
    pre.prettyprint
    {
        border: 0px solid #888;
    }
    ol.linenums
    {
        margin-top: 0;
        margin-bottom: 0;
    }
    .prettyprint {
        background: #000;
    }
    li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9
    {
        color: #555;
        list-style-type: decimal;
    }
    li.L1, li.L3, li.L5, li.L7, li.L9 {
        background: #111;
    }
    @media print
    {
        .str
        {
            color: #060;
        }
        .kwd
        {
            color: #006;
            font-weight: bold;
        }
        .com
        {
            color: #600;
            font-style: italic;
        }
        .typ
        {
            color: #404;
            font-weight: bold;
        }
        .lit
        {
            color: #044;
        }
        .pun
        {
            color: #440;
        }
        .pln
        {
            color: #000;
        }
        .tag
        {
            color: #006;
            font-weight: bold;
        }
        .atn
        {
            color: #404;
        }
        .atv
        {
            color: #060;
        }
    }
    �����������������prettify-2013.03.04/styles/sunburst.css�������������������������������������������������������������0000640�0001750�0001750�00000003631�12115200050�016317� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Pretty printing styles. Used with prettify.js. */
    /* Vim sunburst theme by David Leibovic */
    
    pre .str, code .str { color: #65B042; } /* string  - green */
    pre .kwd, code .kwd { color: #E28964; } /* keyword - dark pink */
    pre .com, code .com { color: #AEAEAE; font-style: italic; } /* comment - gray */
    pre .typ, code .typ { color: #89bdff; } /* type - light blue */
    pre .lit, code .lit { color: #3387CC; } /* literal - blue */
    pre .pun, code .pun { color: #fff; } /* punctuation - white */
    pre .pln, code .pln { color: #fff; } /* plaintext - white */
    pre .tag, code .tag { color: #89bdff; } /* html/xml tag    - light blue */
    pre .atn, code .atn { color: #bdb76b; } /* html/xml attribute name  - khaki */
    pre .atv, code .atv { color: #65B042; } /* html/xml attribute value - green */
    pre .dec, code .dec { color: #3387CC; } /* decimal - blue */
    
    pre.prettyprint, code.prettyprint {
    	background-color: #000;
    	-moz-border-radius: 8px;
    	-webkit-border-radius: 8px;
    	-o-border-radius: 8px;
    	-ms-border-radius: 8px;
    	-khtml-border-radius: 8px;
    	border-radius: 8px;
    }
    
    pre.prettyprint {
    	width: 95%;
    	margin: 1em auto;
    	padding: 1em;
    	white-space: pre-wrap;
    }
    
    
    /* Specify class=linenums on a pre to get line numbering */
    ol.linenums { margin-top: 0; margin-bottom: 0; color: #AEAEAE; } /* IE indents via margin-left */
    li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 { list-style-type: none }
    /* Alternate shading for lines */
    li.L1,li.L3,li.L5,li.L7,li.L9 { }
    
    @media print {
      pre .str, code .str { color: #060; }
      pre .kwd, code .kwd { color: #006; font-weight: bold; }
      pre .com, code .com { color: #600; font-style: italic; }
      pre .typ, code .typ { color: #404; font-weight: bold; }
      pre .lit, code .lit { color: #044; }
      pre .pun, code .pun { color: #440; }
      pre .pln, code .pln { color: #000; }
      pre .tag, code .tag { color: #006; font-weight: bold; }
      pre .atn, code .atn { color: #404; }
      pre .atv, code .atv { color: #060; }
    }
    �������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/doxy.css�����������������������������������������������������������������0000640�0001750�0001750�00000005246�12115200050�015421� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Doxy pretty-printing styles. Used with prettify.js.  */
    
    pre .str, code .str { color: #fec243; } /* string  - eggyolk gold */
    pre .kwd, code .kwd { color: #8470FF; } /* keyword - light slate blue */
    pre .com, code .com { color: #32cd32; font-style: italic; } /* comment - green */
    pre .typ, code .typ { color: #6ecbcc; } /* type - turq green */
    pre .lit, code .lit { color: #d06; } /* literal - cherry red */
    pre .pun, code .pun { color: #8B8970;  } /* punctuation - lemon chiffon4  */
    pre .pln, code .pln { color: #f0f0f0; } /* plaintext - white */
    pre .tag, code .tag { color: #9c9cff; } /* html/xml tag  (bluey)  */
    pre .htm, code .htm { color: #dda0dd; } /* html tag  light purply*/
    pre .xsl, code .xsl { color: #d0a0d0; } /* xslt tag  light purply*/
    pre .atn, code .atn { color: #46eeee; font-weight: normal;} /* html/xml attribute name  - lt turquoise */
    pre .atv, code .atv { color: #EEB4B4; } /* html/xml attribute value - rosy brown2 */
    pre .dec, code .dec { color: #3387CC; } /* decimal - blue */
    
    a {
      text-decoration: none;
    }
    pre.prettyprint, code.prettyprint {
      font-family:'Droid Sans Mono','CPMono_v07 Bold','Droid Sans';
      font-weight: bold;
      font-size: 9pt;
      background-color: #0f0f0f;
      -moz-border-radius: 8px;
      -webkit-border-radius: 8px;
      -o-border-radius: 8px;
      -ms-border-radius: 8px;
      -khtml-border-radius: 8px;
      border-radius: 8px;
    }  /*  background is black (well, just a tad less dark )  */
    
    pre.prettyprint {
      width: 95%;
      margin: 1em auto;
      padding: 1em;
      white-space: pre-wrap;
    }
    
    pre.prettyprint a, code.prettyprint a {
       text-decoration:none;
    }
    /* Specify class=linenums on a pre to get line numbering; line numbers themselves are the same color as punctuation */
    ol.linenums { margin-top: 0; margin-bottom: 0; color: #8B8970; } /* IE indents via margin-left */
    li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 { list-style-type: none }
    /* Alternate shading for lines */
    li.L1,li.L3,li.L5,li.L7,li.L9 { }
    
    /* print is mostly unchanged from default at present  */
    @media print {
      pre.prettyprint, code.prettyprint { background-color: #fff;  }
      pre .str, code .str { color: #088; }
      pre .kwd, code .kwd { color: #006; font-weight: bold; }
      pre .com, code .com { color: #oc3; font-style: italic; }
      pre .typ, code .typ { color: #404; font-weight: bold; }
      pre .lit, code .lit { color: #044; }
      pre .pun, code .pun { color: #440; }
      pre .pln, code .pln { color: #000; }
      pre .tag, code .tag { color: #b66ff7; font-weight: bold; }
      pre .htm, code .htm { color: #606; font-weight: bold; }
      pre .xsl, code .xsl { color: #606; font-weight: bold; }
      pre .atn, code .atn { color: #c71585;  font-weight: normal; }
      pre .atv, code .atv { color: #088;  font-weight: normal; }
    }
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/desert.css���������������������������������������������������������������0000640�0001750�0001750�00000003155�12115200050�015721� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* desert scheme ported from vim to google prettify */
    pre.prettyprint { display: block; background-color: #333 }
    pre .nocode { background-color: none; color: #000 }
    pre .str { color: #ffa0a0 } /* string  - pink */
    pre .kwd { color: #f0e68c; font-weight: bold }
    pre .com { color: #87ceeb } /* comment - skyblue */
    pre .typ { color: #98fb98 } /* type    - lightgreen */
    pre .lit { color: #cd5c5c } /* literal - darkred */
    pre .pun { color: #fff }    /* punctuation */
    pre .pln { color: #fff }    /* plaintext */
    pre .tag { color: #f0e68c; font-weight: bold } /* html/xml tag    - lightyellow */
    pre .atn { color: #bdb76b; font-weight: bold } /* attribute name  - khaki */
    pre .atv { color: #ffa0a0 } /* attribute value - pink */
    pre .dec { color: #98fb98 } /* decimal         - lightgreen */
    
    /* Specify class=linenums on a pre to get line numbering */
    ol.linenums { margin-top: 0; margin-bottom: 0; color: #AEAEAE } /* IE indents via margin-left */
    li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 { list-style-type: none }
    /* Alternate shading for lines */
    li.L1,li.L3,li.L5,li.L7,li.L9 { }
    
    @media print {
      pre.prettyprint { background-color: none }
      pre .str, code .str { color: #060 }
      pre .kwd, code .kwd { color: #006; font-weight: bold }
      pre .com, code .com { color: #600; font-style: italic }
      pre .typ, code .typ { color: #404; font-weight: bold }
      pre .lit, code .lit { color: #044 }
      pre .pun, code .pun { color: #440 }
      pre .pln, code .pln { color: #000 }
      pre .tag, code .tag { color: #006; font-weight: bold }
      pre .atn, code .atn { color: #404 }
      pre .atv, code .atv { color: #060 }
    }
    �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/styles/demo.html����������������������������������������������������������������0000640�0001750�0001750�00000003306�12115200050�015531� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
    <html><head>
    <script src="../src/prettify.js"></script>
    <script src="../src/lang-css.js"></script>
    <style>
    body { margin: 0; padding: 0 }
    pre { margin: 0 }
    </style>
    </head>
    <script>
    // This page displays some code styled using a theme named in the
    // query part of the URL.
    var themeName = decodeURIComponent(document.location.search.replace(/^\?/, ''));
    
    // Call out to the parent so that it can resize the iframe once this
    // document's body is loaded.
    function adjustHeightInParent() {
      if (parent !== window) {
        try {
          var div = document.body.getElementsByTagName('div')[0];
          parent.adjustChildIframeSize(
              themeName, div.offsetWidth, div.offsetHeight);
        } catch (ex) {
          // Can happen when this page is opened in its own tab.
        }
      }
    }
    
    // Load the necessary CSS
    (function () {
      document.title = 'Theme ' + themeName;
      // Load the stylesheet that we're demoing.
      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.href = themeName === 'default'
          ? '../src/prettify.css' : themeName + '.css';
      document.getElementsByTagName('head')[0].appendChild(link);
    })();
    </script>
    
    <body onload="prettyPrint(); adjustHeightInParent()">
    <div style="width: 40em; display: inline-block">
    <pre class="prettyprint lang-html linenums">
    &lt;script type="text/javascript"&gt;
    // Say hello world until the user starts questioning
    // the meaningfulness of their existence.
    function helloWorld(world) {
      for (var i = 42; --i &gt;= 0;) {
        alert('Hello ' + String(world));
      }
    }
    &lt;/script&gt;
    &lt;style&gt;
    p { color: pink }
    b { color: blue }
    u { color: "umber" }
    &lt;/style&gt;
    </pre>
    </div>
    </body></html>
    ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/tools/��������������������������������������������������������������������������0000751�0001750�0001750�00000000000�12362771437�013564� 5����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/tools/lang-handler-aliases.sh���������������������������������������������������0000750�0001750�0001750�00000003644�12115200050�020052� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash
    
    LANG_DIR="$1"
    shift
    
    HAS_LANG_FILES=1
    if echo "$LANG_DIR"/lang-*.js | egrep -q "[*]" >& /dev/null; then
      HAS_LANG_FILES=0
    fi
    
    if [ -n "$*" ] || [ -z "$LANG_DIR" ] || ! (( $HAS_LANG_FILES )); then
      echo "Usage: $0 <LANG_DIR>"
      echo
      echo "Dumps lines of the form"
      echo "    $LANG_DIR/lang-foo.js $LANG_DIR/lang-<extension>.js"
      echo "where the first element is a path name under LANG_DIR"
      echo "and the second is the name of a language extension for which"
      echo "it registers an extension."
      exit -1
    fi
    
    if [ -z "$JS_INTERPRETER" ]; then
      JS_INTERPRETER="jsc-1"
    fi
    
    if ! which "$JS_INTERPRETER" >& /dev/null; then
      echo "\$JS_INTERPRETER ( '$JS_INTERPRETER' ) is not on the \$PATH."
      echo "It should be an executable that loads each argument as a JS file"
      echo "and runs them in a context where the print function dumps a string"
      echo "to stdout."
      exit -1
    fi
    
    for JS in "$LANG_DIR"/lang-*.js; do
      # Run the language handler in a context where PR.registerLangHandler
      # dumps out the handler names without doing anything else, and
      # then use a perl script that prepends each handler with the basename
      # of the JS file.
      # The JS interpreter is run with STDIN of /dev/null so that it does not
      # hand waiting for REPL input.
      ("$JS_INTERPRETER" \
        <(echo '
    
          var window = this;
          var PR = {
            registerLangHandler: function (_, exts) {
              for (var i = 0, n = exts.length; i < n; ++i) {
                var handler = String(exts[i]);
                if (/^\w+$/.test(handler)) {
                  print(handler);
                }
              }
            },
            createSimpleLexer: function () {},
            sourceDecorator:   function () {}
          };
    
          ') \
        \
        "$JS" \
        < /dev/null \
       || echo "Failed to execute $JS" 1>&2 ) \
        | perl -e '$JS=shift;' \
          -e 'use File::Basename; $DIR=dirname($JS);' \
          -e 'while (<STDIN>) { s/^\w+$/$JS $DIR\/lang-$&.js/; print; }' \
          "$JS"
    done
    ��������������������������������������������������������������������������������������������prettify-2013.03.04/tools/cut-release.sh������������������������������������������������������������0000751�0001750�0001750�00000014553�12115200050�016312� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash
    
    function help_and_exit() {
        echo "Usage: $0 [-go] [-verbose] [-force]"
        echo
        echo "Moves minified CSS and JS to distribution directories and"
        echo "creates a branch in SVN."
        echo
        echo "  -go:       Run commands instead of just echoing them."
        echo "  -verbose:  More verbose logging."
        echo "  -force:    Ignore sanity checks for testing."
        echo "             Incompatible with -go."
        echo "  -nobranch: Don't create a new release branch."
        exit "$1"
    }
    
    # 1 for verbose logging
    export VERBOSE="0"
    # 1 if commands that have side-effects should actually be run instead of logged
    export EFFECT="0"
    # 1 to not exit on panic.
    export NO_PANIC="0"
    # 1 to create a new branch under branches/
    export BRANCH="1"
    
    function panic() {
        echo "PANIC: $*"
    
        if ! (( $NO_PANIC )); then
            exit -1
        fi
    }
    
    function command() {
        if (( $VERBOSE )) || ! (( $EFFECT )); then
            echo '$' "$*"
        fi
        if (( $EFFECT )); then
            "$@" || panic "command failed: $@"
        fi
    }
    
    function cp_if_different() {
        if ! [ -e "$2" ] || diffq "$1" "$2"; then
            command cp "$1" "$2"
        fi
    }
    
    function mime_for_file() {
        local path="$1"
        case "${path##*.}" in
            js)   echo -n "text/javascript;charset=UTF-8";;
            css)  echo -n "text/css;charset=UTF-8";;
            html) echo -n "text/html;charset=UTF-8";;
            *)    panic "unrecognized extension for $path";;
        esac
    }
    
    for var in "$@"; do
      case "$var" in
          -verbose)
              VERBOSE="1"
              ;;
          -go)
              EFFECT="1"
              ;;
          -force)
              NO_PANIC="1"
              ;;
          -nobranch)
              BRANCH="0"
              ;;
          -h)
              help_and_exit 0
              ;;
          *)
              echo "Unrecognized argument $var"
              help_and_exit -1
              ;;
      esac
    done
    
    if (( $NO_PANIC )) && (( $EFFECT )); then
        NO_PANIC="0"
        panic "-force is incompatible with -go"
    fi
    
    # Find svn root
    export VERSION_BASE="$(
      pushd "$(dirname "$0")/../.." > /dev/null; pwd; popd > /dev/null)"
    
    if [ -z "$VERSION_BASE" ] || ! [ -d "$VERSION_BASE" ]; then
        panic "unknown VERSION_BASE"
    fi
    if ! [ -d "$VERSION_BASE/trunk" ]; then
        panic "missing trunk in $VERSION_BASE"
    fi
    if ! [ -d "$VERSION_BASE/loader" ]; then
        panic "missing loader in $VERSION_BASE"
    fi
    if (( $BRANCH )) && ! [ -d "$VERSION_BASE/branches" ]; then
        panic "missing branches in $VERSION_BASE"
    fi
    
    if (( $VERBOSE )); then
        echo "VERSION_BASE=$VERSION_BASE"
    fi
    
    # Choose a release label
    # %e has a leading 0.  get rid of that.
    export TODAY="$(date -u +%e-%b-%Y | perl -pe 's/\s+//g')"
    export RELEASE_LABEL="release-$TODAY"
    
    if (( $VERBOSE )); then
        echo "RELEASE_LABEL=$RELEASE_LABEL"
    fi
    
    if (( $BRANCH )) && [ -e "$VERSION_BASE/branches/$RELEASE_LABEL" ]; then
        panic "duplicate release $VERSION_BASE/branches/$RELEASE_LABEL"
    fi
    
    
    # Make the distribution
    function build() {
      pushd "$VERSION_BASE/trunk" > /dev/null
      make clean \
        && make distrib distrib/prettify.tar.bz2 distrib/prettify-small.tar.bz2 \
        && make lang-aliases
      local status=$?
      popd > /dev/null
      (($status))
    }
    if build; then
      panic "Make failed"
    fi
    
    if [ -n "$(svn stat "$VERSION_BASE/trunk")" ]; then
      svn stat "$VERSION_BASE/trunk"
      panic "Uncommitted changes"
    fi
    
    function diffq() {
        ! diff -q "$@" > /dev/null
    }
    
    function sync() {
        local action="$1"
        local src_dir="$2"
        local dest_dir="$3"
        shift 3
        local exts=$@
        local ext
        local src_file
        local dest_file
        (
            shopt -s nullglob
            for ext in $exts; do
                for src_file in "$src_dir"/*."$ext"; do
                    dest_file="$dest_dir"/"$(basename "$src_file")"
                    if ! [ -e "$dest_file" ] || \
                        diffq "$src_file" "$dest_file"; then
                        "$action" "$src_file" "$dest_file"
                    fi
                done
                for dest_file in "$dest_dir"/*."$ext"; do
                    src_file="$src_dir"/"$(basename "$dest_file")"
                    if ! [ -e "$src_file" ]; then
                        "$action" "$src_file" "$dest_file"
                    fi
                done
            done
        )
    }
    
    function svn_sync() {
        local src_file="$1"
        local dest_file="$2"
        if ! [ -e "$src_file" ]; then
            command svn delete "$dest_file"
        else
            # Require lower-7 octets only so that it can be served even without
            # the UTF-8 charset header.
            if ! perl -ne 'exit -1 if m/[^\x00-\x7f]/' "$src_file"; then
                panic "Non-ascii export $src_file"
            fi
            if [ -e "$dest_file" ]; then
                cp_if_different "$src_file" "$dest_file"
            else
                command cp "$src_file" "$dest_file"
                command svn add "$dest_file"
                command svn propset svn:mime-type "$(mime_for_file "$src_file")" \
                    "$dest_file"
            fi
        fi
    }
    
    # Deploy the current compiled source to /loader
    sync svn_sync "$VERSION_BASE/trunk/distrib/google-code-prettify" \
        "$VERSION_BASE/loader" js css
    sync svn_sync "$VERSION_BASE/trunk/styles" \
        "$VERSION_BASE/loader/skins" css
    
    # Cut branch
    if (( $BRANCH )); then
      command svn copy "$VERSION_BASE/trunk" "$VERSION_BASE/branches/$RELEASE_LABEL"
    fi
    
    cp_if_different "$VERSION_BASE/trunk/distrib/prettify.tar.bz2" \
              "$VERSION_BASE/trunk/distrib/prettify-$TODAY.tar.bz2"
    cp_if_different "$VERSION_BASE/trunk/distrib/prettify-small.tar.bz2" \
              "$VERSION_BASE/trunk/distrib/prettify-small-$TODAY.tar.bz2"
    
    # Dump final instructions for caller.
    echo
    if (( $EFFECT )); then
        echo "Finally run"
        echo "    $ svn commit -m 'Release $RELEASE_LABEL'"
        echo "to commit the new release then run"
        echo "$ $VERSION_BASE/trunk/tools/googlecode_upload.py \\"
        echo "    --summary='Bundle of source files, tests, and documentation' \\"
        echo "    -p google-code-prettify -u mikesamuel \\"
        echo "    --labels='Type-Archive,OpSys-All,Featured' \\"
        echo "    $VERSION_BASE/trunk/distrib/prettify-$TODAY.tar.bz2"
        echo "$ $VERSION_BASE/trunk/tools/googlecode_upload.py \\"
        echo "    --summary='Minimized JS and CSS sources' \\"
        echo "    -p google-code-prettify -u mikesamuel \\"
        echo "    --labels='Type-Archive,OpSys-All,Featured' \\"
        echo "    $VERSION_BASE/trunk/distrib/prettify-small-$TODAY.tar.bz2"
        echo "and finally check"
        echo "    http://code.google.com/p/google-code-prettify/downloads/list"
    else
       echo "Rerun with -go flag to actually execute these commands."
    fi
    
    exit 0
    �����������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/tools/googlecode_upload.py������������������������������������������������������0000751�0001750�0001750�00000021760�12115200050�017570� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python
    #
    # Copyright 2006, 2007 Google Inc. All Rights Reserved.
    # Author: danderson@google.com (David Anderson)
    #
    # Script for uploading files to a Google Code project.
    #
    # This is intended to be both a useful script for people who want to
    # streamline project uploads and a reference implementation for
    # uploading files to Google Code projects.
    #
    # To upload a file to Google Code, you need to provide a path to the
    # file on your local machine, a small summary of what the file is, a
    # project name, and a valid account that is a member or owner of that
    # project.  You can optionally provide a list of labels that apply to
    # the file.  The file will be uploaded under the same name that it has
    # in your local filesystem (that is, the "basename" or last path
    # component).  Run the script with '--help' to get the exact syntax
    # and available options.
    #
    # Note that the upload script requests that you enter your
    # googlecode.com password.  This is NOT your Gmail account password!
    # This is the password you use on googlecode.com for committing to
    # Subversion and uploading files.  You can find your password by going
    # to http://code.google.com/hosting/settings when logged in with your
    # Gmail account. If you have already committed to your project's
    # Subversion repository, the script will automatically retrieve your
    # credentials from there (unless disabled, see the output of '--help'
    # for details).
    #
    # If you are looking at this script as a reference for implementing
    # your own Google Code file uploader, then you should take a look at
    # the upload() function, which is the meat of the uploader.  You
    # basically need to build a multipart/form-data POST request with the
    # right fields and send it to https://PROJECT.googlecode.com/files .
    # Authenticate the request using HTTP Basic authentication, as is
    # shown below.
    #
    # Licensed under the terms of the Apache Software License 2.0:
    #  http://www.apache.org/licenses/LICENSE-2.0
    #
    # Questions, comments, feature requests and patches are most welcome.
    # Please direct all of these to the Google Code users group:
    #  http://groups.google.com/group/google-code-hosting
    
    """Google Code file uploader script.
    """
    
    __author__ = 'danderson@google.com (David Anderson)'
    
    import httplib
    import os.path
    import optparse
    import getpass
    import base64
    import sys
    
    
    def upload(file, project_name, user_name, password, summary, labels=None):
      """Upload a file to a Google Code project's file server.
    
      Args:
        file: The local path to the file.
        project_name: The name of your project on Google Code.
        user_name: Your Google account name.
        password: The googlecode.com password for your account.
                  Note that this is NOT your global Google Account password!
        summary: A small description for the file.
        labels: an optional list of label strings with which to tag the file.
    
      Returns: a tuple:
        http_status: 201 if the upload succeeded, something else if an
                     error occured.
        http_reason: The human-readable string associated with http_status
        file_url: If the upload succeeded, the URL of the file on Google
                  Code, None otherwise.
      """
      # The login is the user part of user@gmail.com. If the login provided
      # is in the full user@domain form, strip it down.
      if user_name.endswith('@gmail.com'):
        user_name = user_name[:user_name.index('@gmail.com')]
    
      form_fields = [('summary', summary)]
      if labels is not None:
        form_fields.extend([('label', l.strip()) for l in labels])
    
      content_type, body = encode_upload_request(form_fields, file)
    
      upload_host = '%s.googlecode.com' % project_name
      upload_uri = '/files'
      auth_token = base64.b64encode('%s:%s'% (user_name, password))
      headers = {
        'Authorization': 'Basic %s' % auth_token,
        'User-Agent': 'Googlecode.com uploader v0.9.4',
        'Content-Type': content_type,
        }
    
      server = httplib.HTTPSConnection(upload_host)
      server.request('POST', upload_uri, body, headers)
      resp = server.getresponse()
      server.close()
    
      if resp.status == 201:
        location = resp.getheader('Location', None)
      else:
        location = None
      return resp.status, resp.reason, location
    
    
    def encode_upload_request(fields, file_path):
      """Encode the given fields and file into a multipart form body.
    
      fields is a sequence of (name, value) pairs. file is the path of
      the file to upload. The file will be uploaded to Google Code with
      the same file name.
    
      Returns: (content_type, body) ready for httplib.HTTP instance
      """
      BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
      CRLF = '\r\n'
    
      body = []
    
      # Add the metadata about the upload first
      for key, value in fields:
        body.extend(
          ['--' + BOUNDARY,
           'Content-Disposition: form-data; name="%s"' % key,
           '',
           value,
           ])
    
      # Now add the file itself
      file_name = os.path.basename(file_path)
      f = open(file_path, 'rb')
      file_content = f.read()
      f.close()
    
      body.extend(
        ['--' + BOUNDARY,
         'Content-Disposition: form-data; name="filename"; filename="%s"'
         % file_name,
         # The upload server determines the mime-type, no need to set it.
         'Content-Type: application/octet-stream',
         '',
         file_content,
         ])
    
      # Finalize the form body
      body.extend(['--' + BOUNDARY + '--', ''])
    
      return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
    
    
    def upload_find_auth(file_path, project_name, summary, labels=None,
                         user_name=None, password=None, tries=3):
      """Find credentials and upload a file to a Google Code project's file server.
    
      file_path, project_name, summary, and labels are passed as-is to upload.
    
      Args:
        file_path: The local path to the file.
        project_name: The name of your project on Google Code.
        summary: A small description for the file.
        labels: an optional list of label strings with which to tag the file.
        config_dir: Path to Subversion configuration directory, 'none', or None.
        user_name: Your Google account name.
        tries: How many attempts to make.
      """
      if user_name is None or password is None:
        from netrc import netrc
        authenticators = netrc().authenticators("code.google.com")
        if authenticators:
          if user_name is None:
            user_name = authenticators[0]
          if password is None:
            password = authenticators[2]
    
      while tries > 0:
        if user_name is None:
          # Read username if not specified or loaded from svn config, or on
          # subsequent tries.
          sys.stdout.write('Please enter your googlecode.com username: ')
          sys.stdout.flush()
          user_name = sys.stdin.readline().rstrip()
        if password is None:
          # Read password if not loaded from svn config, or on subsequent tries.
          print 'Please enter your googlecode.com password.'
          print '** Note that this is NOT your Gmail account password! **'
          print 'It is the password you use to access Subversion repositories,'
          print 'and can be found here: http://code.google.com/hosting/settings'
          password = getpass.getpass()
    
        status, reason, url = upload(file_path, project_name, user_name, password,
                                     summary, labels)
        # Returns 403 Forbidden instead of 401 Unauthorized for bad
        # credentials as of 2007-07-17.
        if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
          # Rest for another try.
          user_name = password = None
          tries = tries - 1
        else:
          # We're done.
          break
    
      return status, reason, url
    
    
    def main():
      parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
                                     '-p PROJECT [options] FILE')
      parser.add_option('-s', '--summary', dest='summary',
                        help='Short description of the file')
      parser.add_option('-p', '--project', dest='project',
                        help='Google Code project name')
      parser.add_option('-u', '--user', dest='user',
                        help='Your Google Code username')
      parser.add_option('-w', '--password', dest='password',
                        help='Your Google Code password')
      parser.add_option('-l', '--labels', dest='labels',
                        help='An optional list of comma-separated labels to attach '
                        'to the file')
    
      options, args = parser.parse_args()
    
      if not options.summary:
        parser.error('File summary is missing.')
      elif not options.project:
        parser.error('Project name is missing.')
      elif len(args) < 1:
        parser.error('File to upload not provided.')
      elif len(args) > 1:
        parser.error('Only one file may be specified.')
    
      file_path = args[0]
    
      if options.labels:
        labels = options.labels.split(',')
      else:
        labels = None
    
      status, reason, url = upload_find_auth(file_path, options.project,
                                             options.summary, labels,
                                             options.user, options.password)
      if url:
        print 'The file was uploaded successfully.'
        print 'URL: %s' % url
        return 0
      else:
        print 'An error occurred. Your file was not uploaded.'
        print 'Google Code upload server said: %s (%s)' % (reason, status)
        return 1
    
    
    if __name__ == '__main__':
      sys.exit(main())
    ����������������prettify-2013.03.04/COPYING�������������������������������������������������������������������������0000640�0001750�0001750�00000025013�12115200050�013426� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
                                     Apache License
                               Version 2.0, January 2004
                            http://www.apache.org/licenses/
    
       TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    
       1. Definitions.
    
          "License" shall mean the terms and conditions for use, reproduction,
          and distribution as defined by Sections 1 through 9 of this document.
    
          "Licensor" shall mean the copyright owner or entity authorized by
          the copyright owner that is granting the License.
    
          "Legal Entity" shall mean the union of the acting entity and all
          other entities that control, are controlled by, or are under common
          control with that entity. For the purposes of this definition,
          "control" means (i) the power, direct or indirect, to cause the
          direction or management of such entity, whether by contract or
          otherwise, or (ii) ownership of fifty percent (50%) or more of the
          outstanding shares, or (iii) beneficial ownership of such entity.
    
          "You" (or "Your") shall mean an individual or Legal Entity
          exercising permissions granted by this License.
    
          "Source" form shall mean the preferred form for making modifications,
          including but not limited to software source code, documentation
          source, and configuration files.
    
          "Object" form shall mean any form resulting from mechanical
          transformation or translation of a Source form, including but
          not limited to compiled object code, generated documentation,
          and conversions to other media types.
    
          "Work" shall mean the work of authorship, whether in Source or
          Object form, made available under the License, as indicated by a
          copyright notice that is included in or attached to the work
          (an example is provided in the Appendix below).
    
          "Derivative Works" shall mean any work, whether in Source or Object
          form, that is based on (or derived from) the Work and for which the
          editorial revisions, annotations, elaborations, or other modifications
          represent, as a whole, an original work of authorship. For the purposes
          of this License, Derivative Works shall not include works that remain
          separable from, or merely link (or bind by name) to the interfaces of,
          the Work and Derivative Works thereof.
    
          "Contribution" shall mean any work of authorship, including
          the original version of the Work and any modifications or additions
          to that Work or Derivative Works thereof, that is intentionally
          submitted to Licensor for inclusion in the Work by the copyright owner
          or by an individual or Legal Entity authorized to submit on behalf of
          the copyright owner. For the purposes of this definition, "submitted"
          means any form of electronic, verbal, or written communication sent
          to the Licensor or its representatives, including but not limited to
          communication on electronic mailing lists, source code control systems,
          and issue tracking systems that are managed by, or on behalf of, the
          Licensor for the purpose of discussing and improving the Work, but
          excluding communication that is conspicuously marked or otherwise
          designated in writing by the copyright owner as "Not a Contribution."
    
          "Contributor" shall mean Licensor and any individual or Legal Entity
          on behalf of whom a Contribution has been received by Licensor and
          subsequently incorporated within the Work.
    
       2. Grant of Copyright License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          copyright license to reproduce, prepare Derivative Works of,
          publicly display, publicly perform, sublicense, and distribute the
          Work and such Derivative Works in Source or Object form.
    
       3. Grant of Patent License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          (except as stated in this section) patent license to make, have made,
          use, offer to sell, sell, import, and otherwise transfer the Work,
          where such license applies only to those patent claims licensable
          by such Contributor that are necessarily infringed by their
          Contribution(s) alone or by combination of their Contribution(s)
          with the Work to which such Contribution(s) was submitted. If You
          institute patent litigation against any entity (including a
          cross-claim or counterclaim in a lawsuit) alleging that the Work
          or a Contribution incorporated within the Work constitutes direct
          or contributory patent infringement, then any patent licenses
          granted to You under this License for that Work shall terminate
          as of the date such litigation is filed.
    
       4. Redistribution. You may reproduce and distribute copies of the
          Work or Derivative Works thereof in any medium, with or without
          modifications, and in Source or Object form, provided that You
          meet the following conditions:
    
          (a) You must give any other recipients of the Work or
              Derivative Works a copy of this License; and
    
          (b) You must cause any modified files to carry prominent notices
              stating that You changed the files; and
    
          (c) You must retain, in the Source form of any Derivative Works
              that You distribute, all copyright, patent, trademark, and
              attribution notices from the Source form of the Work,
              excluding those notices that do not pertain to any part of
              the Derivative Works; and
    
          (d) If the Work includes a "NOTICE" text file as part of its
              distribution, then any Derivative Works that You distribute must
              include a readable copy of the attribution notices contained
              within such NOTICE file, excluding those notices that do not
              pertain to any part of the Derivative Works, in at least one
              of the following places: within a NOTICE text file distributed
              as part of the Derivative Works; within the Source form or
              documentation, if provided along with the Derivative Works; or,
              within a display generated by the Derivative Works, if and
              wherever such third-party notices normally appear. The contents
              of the NOTICE file are for informational purposes only and
              do not modify the License. You may add Your own attribution
              notices within Derivative Works that You distribute, alongside
              or as an addendum to the NOTICE text from the Work, provided
              that such additional attribution notices cannot be construed
              as modifying the License.
    
          You may add Your own copyright statement to Your modifications and
          may provide additional or different license terms and conditions
          for use, reproduction, or distribution of Your modifications, or
          for any such Derivative Works as a whole, provided Your use,
          reproduction, and distribution of the Work otherwise complies with
          the conditions stated in this License.
    
       5. Submission of Contributions. Unless You explicitly state otherwise,
          any Contribution intentionally submitted for inclusion in the Work
          by You to the Licensor shall be under the terms and conditions of
          this License, without any additional terms or conditions.
          Notwithstanding the above, nothing herein shall supersede or modify
          the terms of any separate license agreement you may have executed
          with Licensor regarding such Contributions.
    
       6. Trademarks. This License does not grant permission to use the trade
          names, trademarks, service marks, or product names of the Licensor,
          except as required for reasonable and customary use in describing the
          origin of the Work and reproducing the content of the NOTICE file.
    
       7. Disclaimer of Warranty. Unless required by applicable law or
          agreed to in writing, Licensor provides the Work (and each
          Contributor provides its Contributions) on an "AS IS" BASIS,
          WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          implied, including, without limitation, any warranties or conditions
          of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          PARTICULAR PURPOSE. You are solely responsible for determining the
          appropriateness of using or redistributing the Work and assume any
          risks associated with Your exercise of permissions under this License.
    
       8. Limitation of Liability. In no event and under no legal theory,
          whether in tort (including negligence), contract, or otherwise,
          unless required by applicable law (such as deliberate and grossly
          negligent acts) or agreed to in writing, shall any Contributor be
          liable to You for damages, including any direct, indirect, special,
          incidental, or consequential damages of any character arising as a
          result of this License or out of the use or inability to use the
          Work (including but not limited to damages for loss of goodwill,
          work stoppage, computer failure or malfunction, or any and all
          other commercial damages or losses), even if such Contributor
          has been advised of the possibility of such damages.
    
       9. Accepting Warranty or Additional Liability. While redistributing
          the Work or Derivative Works thereof, You may choose to offer,
          and charge a fee for, acceptance of support, warranty, indemnity,
          or other liability obligations and/or rights consistent with this
          License. However, in accepting such obligations, You may act only
          on Your own behalf and on Your sole responsibility, not on behalf
          of any other Contributor, and only if You agree to indemnify,
          defend, and hold each Contributor harmless for any liability
          incurred by, or claims asserted against, such Contributor by reason
          of your accepting any such warranty or additional liability.
    
       END OF TERMS AND CONDITIONS
    
       Copyright 2011 Mike Samuel et al
    
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
    
           http://www.apache.org/licenses/LICENSE-2.0
    
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
    ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/���������������������������������������������������������������������0000751�0001750�0001750�00000000000�12362767251�014505� 5����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/externs.js�����������������������������������������������������������0000640�0001750�0001750�00000001720�12115200050�016502� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������var PR = {};
    
    /**
     * @param {function (Object)} handler
     * @param {Array.<string>} fileExtensions
     */
    PR.registerLangHandler = function registerLangHandler(handler, fileExtensions) {};
    
    /**
     * @param {Array} shortcutStylePatterns
     * @param {Array} fallthroughStylePatterns
     * @return {function (Object)}
     */
    PR.createSimpleLexer = function createSimpleLexer(
      shortcutStylePatterns, fallthroughStylePatterns) {};
    
    /**
     * @param {Object} options a set of optional parameters.
     * @return {function (Object)} a function that examines the source code
     *     in the input job and builds the decoration list.
     */
    PR.sourceDecorator = function sourceDecorator(options) {};
    
    
    PR.PR_ATTRIB_NAME = 'atn';
    PR.PR_ATTRIB_VALUE = 'atv';
    PR.PR_COMMENT = 'com';
    PR.PR_DECLARATION = 'dec';
    PR.PR_KEYWORD = 'kwd';
    PR.PR_LITERAL = 'lit';
    PR.PR_NOCODE = 'nocode';
    PR.PR_PLAIN = 'pln';
    PR.PR_PUNCTUATION = 'pun';
    PR.PR_SOURCE = 'src';
    PR.PR_STRING = 'str';
    PR.PR_TAG = 'tag';
    PR.PR_TYPE = 'typ';
    ������������������������������������������������prettify-2013.03.04/js-modules/recombineTagsAndDecorations.js���������������������������������������0000640�0001750�0001750�00000010246�12115200050�022415� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/**
     * Breaks {@code job.sourceCode} around style boundaries in
     * {@code job.decorations} and modifies {@code job.sourceNode} in place.
     * @param {Object} job like <pre>{
     *    sourceCode: {string} source as plain text,
     *    sourceNode: {HTMLElement} the element containing the source,
     *    spans: {Array.<number|Node>} alternating span start indices into source
     *       and the text node or element (e.g. {@code <BR>}) corresponding to that
     *       span.
     *    decorations: {Array.<number|string} an array of style classes preceded
     *       by the position at which they start in job.sourceCode in order
     * }</pre>
     * @private
     */
    function recombineTagsAndDecorations(job) {
      var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
      isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
      var newlineRe = /\n/g;
    
      var source = job.sourceCode;
      var sourceLength = source.length;
      // Index into source after the last code-unit recombined.
      var sourceIndex = 0;
    
      var spans = job.spans;
      var nSpans = spans.length;
      // Index into spans after the last span which ends at or before sourceIndex.
      var spanIndex = 0;
    
      var decorations = job.decorations;
      var nDecorations = decorations.length;
      // Index into decorations after the last decoration which ends at or before
      // sourceIndex.
      var decorationIndex = 0;
    
      // Remove all zero-length decorations.
      decorations[nDecorations] = sourceLength;
      var decPos, i;
      for (i = decPos = 0; i < nDecorations;) {
        if (decorations[i] !== decorations[i + 2]) {
          decorations[decPos++] = decorations[i++];
          decorations[decPos++] = decorations[i++];
        } else {
          i += 2;
        }
      }
      nDecorations = decPos;
    
      // Simplify decorations.
      for (i = decPos = 0; i < nDecorations;) {
        var startPos = decorations[i];
        // Conflate all adjacent decorations that use the same style.
        var startDec = decorations[i + 1];
        var end = i + 2;
        while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
          end += 2;
        }
        decorations[decPos++] = startPos;
        decorations[decPos++] = startDec;
        i = end;
      }
    
      nDecorations = decorations.length = decPos;
    
      var sourceNode = job.sourceNode;
      var oldDisplay;
      if (sourceNode) {
        oldDisplay = sourceNode.style.display;
        sourceNode.style.display = 'none';
      }
      try {
        var decoration = null;
        while (spanIndex < nSpans) {
          var spanStart = spans[spanIndex];
          var spanEnd = spans[spanIndex + 2] || sourceLength;
    
          var decEnd = decorations[decorationIndex + 2] || sourceLength;
    
          var end = Math.min(spanEnd, decEnd);
    
          var textNode = spans[spanIndex + 1];
          var styledText;
          if (textNode.nodeType !== 1  // Don't muck with <BR>s or <LI>s
              // Don't introduce spans around empty text nodes.
              && (styledText = source.substring(sourceIndex, end))) {
            // This may seem bizarre, and it is.  Emitting LF on IE causes the
            // code to display with spaces instead of line breaks.
            // Emitting Windows standard issue linebreaks (CRLF) causes a blank
            // space to appear at the beginning of every line but the first.
            // Emitting an old Mac OS 9 line separator makes everything spiffy.
            if (isIE8OrEarlier) {
              styledText = styledText.replace(newlineRe, '\r');
            }
            textNode.nodeValue = styledText;
            var document = textNode.ownerDocument;
            var span = document.createElement('span');
            span.className = decorations[decorationIndex + 1];
            var parentNode = textNode.parentNode;
            parentNode.replaceChild(span, textNode);
            span.appendChild(textNode);
            if (sourceIndex < spanEnd) {  // Split off a text node.
              spans[spanIndex + 1] = textNode
                  // TODO: Possibly optimize by using '' if there's no flicker.
                  = document.createTextNode(source.substring(end, spanEnd));
              parentNode.insertBefore(textNode, span.nextSibling);
            }
          }
    
          sourceIndex = end;
    
          if (sourceIndex >= spanEnd) {
            spanIndex += 2;
          }
          if (sourceIndex >= decEnd) {
            decorationIndex += 2;
          }
        }
      } finally {
        if (sourceNode) {
          sourceNode.style.display = oldDisplay;
        }
      }
    }
    ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/run_prettify.js������������������������������������������������������0000640�0001750�0001750�00000023030�12115200050�017542� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2013 Google Inc.
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    
    // Looks at query parameters to decide which language handlers and style-sheets
    // to load.
    
    // Query Parameter     Format           Effect                        Default
    // +------------------+---------------+------------------------------+--------+
    // | autorun=         | true | false  | If true then prettyPrint()   | "true" |
    // |                  |               | is called on page load.      |        |
    // +------------------+---------------+------------------------------+--------+
    // | lang=            | language name | Loads the language handler   | Can    |
    // |                  |               | named "lang-<NAME>.js".      | appear |
    // |                  |               | See available handlers at    | many   |
    // |                  |               | http://code.google.com/p/    | times. |
    // |                  |               | google-code-prettify/source/ |        |
    // |                  |               | browse/trunk/src             |        |
    // +------------------+---------------+------------------------------+--------+
    // | skin=            | skin name     | Loads the skin stylesheet    | none.  |
    // |                  |               | named "<NAME>.css".          |        |
    // |                  |               | http://code.google.com/p/    |        |
    // |                  |               | google-code-prettify/source/ |        |
    // |                  |               | browse/trunk/styles          |        |
    // +------------------+---------------+------------------------------+--------+
    // | callback=        | JS identifier | When "prettyPrint" finishes  | none   |
    // |                  |               | window.exports[js_ident] is  |        |
    // |                  |               | called.                      |        |
    // |                  |               | The callback must be under   |        |
    // |                  |               | exports to reduce the risk   |        |
    // |                  |               | of XSS via query parameter   |        |
    // |                  |               | injection.                   |        |
    // +------------------+---------------+------------------------------+--------+
    
    // Exmaples
    // .../prettify.js?lang=css&skin=sunburst
    //   1. Loads the CSS language handler which can be used to prettify CSS
    //      stylesheets, HTML <style> element bodies and style="..." attributes
    //      values.
    //   2. Loads the sunburst.css stylesheet instead of the default prettify.css
    //      stylesheet.
    //      A gallery of stylesheets is available at
    //      https://google-code-prettify.googlecode.com/svn/trunk/styles/index.html
    //   3. Since autorun=false is not specified, calls prettyPrint() on page load.
    
    (function () {
      "use strict";
    
      var win = window;
      var setTimeout = win.setTimeout;
      var doc = document;
      var root = doc.documentElement;
      var head = doc['head'] || doc.getElementsByTagName("head")[0] || root;
    
      // From http://javascript.nwbox.com/ContentLoaded/contentloaded.js
      // Author: Diego Perini (diego.perini at gmail.com)
      // Summary: cross-browser wrapper for DOMContentLoaded
      // Updated: 20101020
      // License: MIT
      // Version: 1.2
      function contentLoaded(callback) {
        var addEventListener = doc['addEventListener'];
        var done = false, top = true,
            add = addEventListener ? 'addEventListener' : 'attachEvent',
            rem = addEventListener ? 'removeEventListener' : 'detachEvent',
            pre = addEventListener ? '' : 'on',
    
            init = function(e) {
              if (e.type == 'readystatechange' && doc.readyState != 'complete') {
                return;
              }
              (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
              if (!done && (done = true)) { callback.call(win, e.type || e); }
            },
    
            poll = function() {
              try {
                root.doScroll('left');
              } catch(e) {
                setTimeout(poll, 50);
                return;
              }
              init('poll');
            };
    
        if (doc.readyState == 'complete') {
          callback.call(win, 'lazy');
        } else {
          if (doc.createEventObject && root.doScroll) {
            try { top = !win.frameElement; } catch(e) { }
            if (top) { poll(); }
          }
          doc[add](pre + 'DOMContentLoaded', init, false);
          doc[add](pre + 'readystatechange', init, false);
          win[add](pre + 'load', init, false);
        }
      }
    
      // Given a list of URLs to stylesheets, loads the first that loads without
      // triggering an error event.
      function loadStylesheetsFallingBack(stylesheets) {
        var n = stylesheets.length;
        function load(i) {
          if (i === n) { return; }
          var link = doc.createElement('link');
          link.rel = 'stylesheet';
          link.type = 'text/css';
          if (i + 1 < n) {
            // http://pieisgood.org/test/script-link-events/ indicates that many
            // versions of IE do not support onerror on <link>s, though
            // http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx
            // indicates that recent IEs do support error.
            link.error = link.onerror = function () { load(i + 1); };
          }
          link.href = stylesheets[i];
          head.appendChild(link);
        }
        load(0);
      }
    
      var scriptQuery = '';
      // Look for the <script> node that loads this script to get its parameters.
      // This starts looking at the end instead of just considering the last
      // because deferred and async scripts run out of order.
      // If the script is loaded twice, then this will run in reverse order.
      for (var scripts = doc.scripts, i = scripts.length; --i >= 0;) {
        var script = scripts[i];
        var match = script.src.match(
            /^[^?#]*\/run_prettify\.js(\?[^#]*)?(?:#.*)?$/);
        if (match) {
          scriptQuery = match[1] || '';
          // Remove the script from the DOM so that multiple runs at least run
          // multiple times even if parameter sets are interpreted in reverse
          // order.
          script.parentNode.removeChild(script);
          break;
        }
      }
    
      // Pull parameters into local variables.
      var autorun = true;
      var langs = [];
      var skins = [];
      var callbacks = [];
      scriptQuery.replace(
          /[?&]([^&=]+)=([^&]+)/g,
          function (_, name, value) {
            value = decodeURIComponent(value);
            name = decodeURIComponent(name);
            if (name == 'autorun')   { autorun = !/^[0fn]/i.test(value); } else
            if (name == 'lang')      { langs.push(value);                } else
            if (name == 'skin')      { skins.push(value);                } else
            if (name == 'callback')  { callbacks.push(value);            }
          });
    
      // Use https to avoid mixed content warnings in client pages and to
      // prevent a MITM from rewrite prettify mid-flight.
      // This only works if this script is loaded via https : something
      // over which we exercise no control.
      var LOADER_BASE_URL =
         'https://google-code-prettify.googlecode.com/svn/loader';
    
      for (var i = 0, n = langs.length; i < n; ++i) (function (lang) {
        var script = doc.createElement("script");
    
        // Excerpted from jQuery.ajaxTransport("script") to fire events when
        // a script is finished loading.
        // Attach handlers for each script
        script.onload = script.onerror = script.onreadystatechange = function () {
          if (script && (
                !script.readyState || /loaded|complete/.test(script.readyState))) {
            // Handle memory leak in IE
            script.onerror = script.onload = script.onreadystatechange = null;
    
            --pendingLanguages;
            checkPendingLanguages();
    
            // Remove the script
            if (script.parentNode) {
              script.parentNode.removeChild(script);
            }
    
            script = null;
          }
        };
    
        script.type = 'text/javascript';
        script.src = LOADER_BASE_URL
          + '/lang-' + encodeURIComponent(langs[i]) + '.js';
    
        // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
        head.insertBefore(script, head.firstChild);
      })(langs[i]);
    
      var pendingLanguages = langs.length;
      function checkPendingLanguages() {
        if (!pendingLanguages) {
          setTimeout(onLangsLoaded, 0);
        }
      }
    
      var skinUrls = [];
      for (var i = 0, n = skins.length; i < n; ++i) {
        skinUrls.push(LOADER_BASE_URL
            + '/skins/' + encodeURIComponent(skins[i]) + '.css');
      }
      skinUrls.push(LOADER_BASE_URL + '/prettify.css');
      loadStylesheetsFallingBack(skinUrls);
    
      var prettyPrint = (function () {
        include("prettify.js");
        return prettyPrint;
      })();
    
      // If this script is deferred or async and the document is already
      // loaded we need to wait for language handlers to load before performing
      // any autorun.
      function onLangsLoaded() {
        if (autorun) {
          contentLoaded(
            function () {
              var n = callbacks.length;
              var callback = n ? function () {
                for (var i = 0; i < n; ++i) {
                  (function (i) {
                     setTimeout(
                       function () {
                         win['exports'][callbacks[i]].apply(win, arguments);
                       }, 0);
                   })(i);
                }
              } : void 0;
              prettyPrint(callback);
            });
        }
      }
      checkPendingLanguages();
    
    }());
    ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/recombineTagsAndDecorations_test.html��������������������������������0000640�0001750�0001750�00000007662�12115200050�024014� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
    <html> <head>
    <title>Recombine Tags And Decorations</title>
    <script src="extractSourceSpans.js"></script>
    <script src="numberLines.js"></script>
    <script src="recombineTagsAndDecorations.js"></script>
    <script src="http://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
    <link rel="stylesheet" href="../src/prettify.css" type="text/css" />
    <style>
    .ok { background: #dfd }
    .error, .failure { background: #fdd }
    .error { white-space: pre }
    td { font-family: monospace }
    tr { vertical-align: top }
    </style>
    </head>
    
    <body>
    <h1>Recombine Tags And Decorations</h1>
    
    <table border="1" cellpadding="2" cellspacing="0">
      <tr><th colspan="4">Test Single Decoration</th></tr>
      <tr>
        <td><code class="testinput">"Hello, World!"</code></td>
        <td class="decorations">[0, 'str']</td>
        <td><code><span class="str">"Hello, World!"</span></code></td>
      </tr>
      <tr><th colspan="4">Test Single Span</th></tr>
      <tr>
        <td><code class="testinput">print "Hello, &lt;World&gt;!";</code></td>
        <td class="decorations">[0, 'kwd', 5, 'pln', 6, 'str', 14, 'tag', 21, 'str', 23, 'pun']</td>
        <td><code><span class="kwd">print</span><span class="pln"> </span><span class="str">"Hello, </span><span class="tag">&lt;World&gt;</span><span class="str">!"</span><span class="pun">;</span></code></td>
      </tr>
      <tr><th colspan="4">Test Interleaved</th></tr>
      <tr>
        <td><code class="testinput">print "Hello, &lt;<b>World</b>&gt;!";</code></td>
        <td class="decorations">[0, 'kwd', 5, 'pln', 6, 'str', 14, 'tag', 21, 'str', 23, 'pun']</td>
        <td><code><span class="kwd">print</span><span class="pln"> </span><span class="str">"Hello, </span><span class="tag">&lt;</span><b><span class="tag">World</span></b><span class="tag">&gt;</span><span class="str">!"</span><span class="pun">;</span></code></td>
      </tr>
    </table>
    
    <script>
    if (!document.body.getElementsByClassName) {
      document.body.getElementsByClassName = function (className) {
        className = className.replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ' ');
        var results = [];
        function walk(node) {
          if (node.nodeType !== 1) { return; }
          // This test should be order-insensitive.
          if ((' ' + node.className + ' ').indexOf(className) >= 0) {
            results[results.length] = node;
          }
          for (var child = node.firstChild; child; child = child.nextSibling) {
            walk(child);
          }
        }
        walk(document.body);
        return results;
      };
    }
    
    setTimeout(function () {
      var testInputs = Array.prototype.slice.call(
         document.body.getElementsByClassName('testinput'), 0);
      for (var i = 0, n = testInputs.length; i < n; ++i) {
        var testInput = testInputs[i];
        var decorationsNode = testInput.parentNode.nextSibling;
        while (decorationsNode.nodeType !== 1) { decorationsNode = decorationsNode.nextSibling; }
        var testResult = decorationsNode.nextSibling;
        while (testResult.nodeType !== 1) { testResult = testResult.nextSibling; }
        var actual = document.createElement('TD');
        testResult.parentNode.appendChild(actual);
        var clone = testInput.cloneNode(true);
        clone.className = '';  // IE
        clone.removeAttribute('class');  // Not IE.
        actual.appendChild(clone);
        var job = extractSourceSpans(clone);
        job.decorations = eval(decorationsNode.innerText || decorationsNode.textContent);
        try {
          recombineTagsAndDecorations(job);
          var passed = testResult.innerHTML === actual.innerHTML;
          if (!passed) {
            console.log(JSON.stringify(testResult.innerHTML) + ' !==\n' + JSON.stringify(actual.innerHTML));
          }
          actual.className = passed ? 'ok' : 'failure';
        } catch (ex) {
          actual.className = 'error';
          actual.appendChild(document.createTextNode(
              'Error: ' + (ex.message || ex)  + '\n' + ex.stack));
        }
        actual.className += ' actual';
      }
    }, 0)</script>
    
    <hr>
    <address></address>
    <!-- hhmts start --> Last modified: Tue Mar 29 10:41:34 PDT 2011 <!-- hhmts end -->
    </body> </html>
    ������������������������������������������������������������������������������prettify-2013.03.04/js-modules/extractSourceSpans_test.html�����������������������������������������0000640�0001750�0001750�00000011404�12115200050�022241� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
    <html> <head>
    <title>Extract Source Spans Test</title>
    <script src="extractSourceSpans.js"></script>
    <script src="http://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
    <style>
    .ok { background: #dfd }
    .error, .failure { background: #fdd }
    td { font-family: monospace }
    .actual { white-space: pre }
    tr { vertical-align: top }
    .break { padding-left: 2px; border-right-style: dotted !important }
    .odd, .even { border-style: solid; border-width: 1px }
    .even { background: #fff; border-color: #888 }
    .odd { background: #ddd; border-color: #000 }
    </style>
    </head>
    
    <body>
    <h1>Extract Source Spans Test</h1>
    
    <table border=1 cellpadding=2 cellspacing=0>
      <tr><th colspan=3>Test space preserved in PRE</th></tr>
      <tr>
        <td><pre class="testinput"><b>print </b>'Hello '<br>  + '&lt;World&gt;';</pre></td>
        <td class="golden"><pre>^print ^'Hello '^\n^  + '&lt;World&gt;';^</pre></td>
      </tr>
      <tr><th colspan=3>Test class="nocode"</th></tr>
      <tr>
        <td><pre class="testinput"><span class=nocode>1. </span><b>print </b>'Hello '<br><span class=nocode>2. </span>  + '&lt;World&gt;';</pre></td>
        <td class="golden"><pre>^print ^'Hello '^\n^  + '&lt;World&gt;';^</pre></td>
      </tr>
      <tr><th colspan=3>Test whitespace normalized in code</th></tr>
      <tr>
        <td><code class="testinput"><b>print </b>'Hello '
      + '&lt;World&gt;';</pre></td>
        <td class="golden"><pre>^print ^'Hello ' + '&lt;World&gt;';^</pre></td>
      </tr>
      <tr><th colspan=3>Test XMP</th></tr>
      <tr>
        <td><xmp class="testinput">print 'Hello '
      + '<World>';
        
    ^print 'Hello '\n  + '<World>';^
    Test tabs
    print 'Hello '
    	+ '<World>';
    ^print 'Hello '\n\t+ '<World>';^
    Test number lines output
    • print 'Hello '
    • + '<World>';
  • ^print ^'Hello '^\n^  + '<World>';^^

    Last modified: Tue Mar 29 16:38:23 PDT 2011 prettify-2013.03.04/js-modules/prettify.js0000640000175000017500000012070412115200050016664 0ustar domidomi// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * *

    * For a fairly comprehensive set of languages see the * README * file that came with this source. At a minimum, 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 subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. *

    * Usage:

      *
    1. include this source file in an html page via * {@code } *
    2. define style rules. See the example page for examples. *
    3. mark the {@code
      } and {@code } tags in your source with
       *    {@code class=prettyprint.}
       *    You can also use the (html deprecated) {@code } tag, but the pretty
       *    printer needs to do more substantial DOM manipulations to support that, so
       *    some css styles may not be preserved.
       * </ol>
       * That's it.  I wanted to keep the API as simple as possible, so there's no
       * need to specify which language the code is in, but if you wish, you can add
       * another class to the {@code <pre>} or {@code <code>} element to specify the
       * language, as in {@code <pre class="prettyprint lang-java">}.  Any class that
       * starts with "lang-" followed by a file extension, specifies the file type.
       * See the "lang-*.js" files in this directory for code that implements
       * per-language file handlers.
       * <p>
       * Change log:<br>
       * cbeust, 2006/08/22
       * <blockquote>
       *   Java annotations (start with "@") are now captured as literals ("lit")
       * </blockquote>
       * @requires console
       */
      
      // JSLint declarations
      /*global console, document, navigator, setTimeout, window, define */
      
      /** @define {boolean} */
      var IN_GLOBAL_SCOPE = true;
      
      /**
       * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
       * UI events.
       * If set to {@code false}, {@code prettyPrint()} is synchronous.
       */
      window['PR_SHOULD_USE_CONTINUATION'] = true;
      
      /**
       * Pretty print a chunk of code.
       * @param {string} sourceCodeHtml The HTML to pretty print.
       * @param {string} opt_langExtension The language name to use.
       *     Typically, a filename extension like 'cpp' or 'java'.
       * @param {number|boolean} opt_numberLines True to number lines,
       *     or the 1-indexed number of the first line in sourceCodeHtml.
       * @return {string} code as html, but prettier
       */
      var prettyPrintOne;
      /**
       * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
       * {@code class=prettyprint} and prettify them.
       *
       * @param {Function} opt_whenDone called when prettifying is done.
       * @param {HTMLElement|HTMLDocument} opt_root an element or document
       *   containing all the elements to pretty print.
       *   Defaults to {@code document.body}.
       */
      var prettyPrint;
      
      
      (function () {
        var win = window;
        // Keyword lists for various languages.
        // We use things that coerce to strings to make them compact when minified
        // and to defeat aggressive optimizers that fold large string constants.
        var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
        var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," + 
            "double,enum,extern,float,goto,inline,int,long,register,short,signed," +
            "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
        var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
            "new,operator,private,protected,public,this,throw,true,try,typeof"];
        var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
            "concept,concept_map,const_cast,constexpr,decltype,delegate," +
            "dynamic_cast,explicit,export,friend,generic,late_check," +
            "mutable,namespace,nullptr,property,reinterpret_cast,static_assert," +
            "static_cast,template,typeid,typename,using,virtual,where"];
        var JAVA_KEYWORDS = [COMMON_KEYWORDS,
            "abstract,assert,boolean,byte,extends,final,finally,implements,import," +
            "instanceof,interface,null,native,package,strictfp,super,synchronized," +
            "throws,transient"];
        var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
            "as,base,by,checked,decimal,delegate,descending,dynamic,event," +
            "fixed,foreach,from,group,implicit,in,internal,into,is,let," +
            "lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
            "sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
            "var,virtual,where"];
        var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
            "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
            "throw,true,try,unless,until,when,while,yes";
        var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
            "debugger,eval,export,function,get,null,set,undefined,var,with," +
            "Infinity,NaN"];
        var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
            "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
            "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
        var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
            "elif,except,exec,finally,from,global,import,in,is,lambda," +
            "nonlocal,not,or,pass,print,raise,try,with,yield," +
            "False,True,None"];
        var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
            "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
            "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
            "BEGIN,END"];
         var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," +
            "enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," +
            "pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"];
        var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
            "function,in,local,set,then,until"];
        var ALL_KEYWORDS = [
            CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
            PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
        var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
      
        // token style names.  correspond to css classes
        /**
         * token style for a string literal
         * @const
         */
        var PR_STRING = 'str';
        /**
         * token style for a keyword
         * @const
         */
        var PR_KEYWORD = 'kwd';
        /**
         * token style for a comment
         * @const
         */
        var PR_COMMENT = 'com';
        /**
         * token style for a type
         * @const
         */
        var PR_TYPE = 'typ';
        /**
         * token style for a literal value.  e.g. 1, null, true.
         * @const
         */
        var PR_LITERAL = 'lit';
        /**
         * token style for a punctuation string.
         * @const
         */
        var PR_PUNCTUATION = 'pun';
        /**
         * token style for plain text.
         * @const
         */
        var PR_PLAIN = 'pln';
      
        /**
         * token style for an sgml tag.
         * @const
         */
        var PR_TAG = 'tag';
        /**
         * token style for a markup declaration such as a DOCTYPE.
         * @const
         */
        var PR_DECLARATION = 'dec';
        /**
         * token style for embedded source.
         * @const
         */
        var PR_SOURCE = 'src';
        /**
         * token style for an sgml attribute name.
         * @const
         */
        var PR_ATTRIB_NAME = 'atn';
        /**
         * token style for an sgml attribute value.
         * @const
         */
        var PR_ATTRIB_VALUE = 'atv';
      
        /**
         * A class that indicates a section of markup that is not code, e.g. to allow
         * embedding of line numbers within code listings.
         * @const
         */
        var PR_NOCODE = 'nocode';
      
        include("regexpPrecederPatterns.pl");
      
        include("combinePrefixPatterns.js");
      
        include("extractSourceSpans.js");
      
        /**
         * Apply the given language handler to sourceCode and add the resulting
         * decorations to out.
         * @param {number} basePos the index of sourceCode within the chunk of source
         *    whose decorations are already present on out.
         */
        function appendDecorations(basePos, sourceCode, langHandler, out) {
          if (!sourceCode) { return; }
          var job = {
            sourceCode: sourceCode,
            basePos: basePos
          };
          langHandler(job);
          out.push.apply(out, job.decorations);
        }
      
        var notWs = /\S/;
      
        /**
         * Given an element, if it contains only one child element and any text nodes
         * it contains contain only space characters, return the sole child element.
         * Otherwise returns undefined.
         * <p>
         * This is meant to return the CODE element in {@code <pre><code ...>} when
         * there is a single child element that contains all the non-space textual
         * content, but not to return anything where there are multiple child elements
         * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
         * is textual content.
         */
        function childContentWrapper(element) {
          var wrapper = undefined;
          for (var c = element.firstChild; c; c = c.nextSibling) {
            var type = c.nodeType;
            wrapper = (type === 1)  // Element Node
                ? (wrapper ? element : c)
                : (type === 3)  // Text Node
                ? (notWs.test(c.nodeValue) ? element : wrapper)
                : wrapper;
          }
          return wrapper === element ? undefined : wrapper;
        }
      
        /** Given triples of [style, pattern, context] returns a lexing function,
          * The lexing function interprets the patterns to find token boundaries and
          * returns a decoration list of the form
          * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
          * where index_n is an index into the sourceCode, and style_n is a style
          * constant like PR_PLAIN.  index_n-1 <= index_n, and style_n-1 applies to
          * all characters in sourceCode[index_n-1:index_n].
          *
          * The stylePatterns is a list whose elements have the form
          * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
          *
          * Style is a style constant like PR_PLAIN, or can be a string of the
          * form 'lang-FOO', where FOO is a language extension describing the
          * language of the portion of the token in $1 after pattern executes.
          * E.g., if style is 'lang-lisp', and group 1 contains the text
          * '(hello (world))', then that portion of the token will be passed to the
          * registered lisp handler for formatting.
          * The text before and after group 1 will be restyled using this decorator
          * so decorators should take care that this doesn't result in infinite
          * recursion.  For example, the HTML lexer rule for SCRIPT elements looks
          * something like ['lang-js', /<[s]cript>(.+?)<\/script>/].  This may match
          * '<script>foo()<\/script>', which would cause the current decorator to
          * be called with '<script>' which would not match the same rule since
          * group 1 must not be empty, so it would be instead styled as PR_TAG by
          * the generic tag rule.  The handler registered for the 'js' extension would
          * then be called with 'foo()', and finally, the current decorator would
          * be called with '<\/script>' which would not match the original rule and
          * so the generic tag rule would identify it as a tag.
          *
          * Pattern must only match prefixes, and if it matches a prefix, then that
          * match is considered a token with the same style.
          *
          * Context is applied to the last non-whitespace, non-comment token
          * recognized.
          *
          * Shortcut is an optional string of characters, any of which, if the first
          * character, gurantee that this pattern and only this pattern matches.
          *
          * @param {Array} shortcutStylePatterns patterns that always start with
          *   a known character.  Must have a shortcut string.
          * @param {Array} fallthroughStylePatterns patterns that will be tried in
          *   order if the shortcut ones fail.  May have shortcuts.
          *
          * @return {function (Object)} a
          *   function that takes source code and returns a list of decorations.
          */
        function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
          var shortcuts = {};
          var tokenizer;
          (function () {
            var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
            var allRegexs = [];
            var regexKeys = {};
            for (var i = 0, n = allPatterns.length; i < n; ++i) {
              var patternParts = allPatterns[i];
              var shortcutChars = patternParts[3];
              if (shortcutChars) {
                for (var c = shortcutChars.length; --c >= 0;) {
                  shortcuts[shortcutChars.charAt(c)] = patternParts;
                }
              }
              var regex = patternParts[1];
              var k = '' + regex;
              if (!regexKeys.hasOwnProperty(k)) {
                allRegexs.push(regex);
                regexKeys[k] = null;
              }
            }
            allRegexs.push(/[\0-\uffff]/);
            tokenizer = combinePrefixPatterns(allRegexs);
          })();
      
          var nPatterns = fallthroughStylePatterns.length;
      
          /**
           * Lexes job.sourceCode and produces an output array job.decorations of
           * style classes preceded by the position at which they start in
           * job.sourceCode in order.
           *
           * @param {Object} job an object like <pre>{
           *    sourceCode: {string} sourceText plain text,
           *    basePos: {int} position of job.sourceCode in the larger chunk of
           *        sourceCode.
           * }</pre>
           */
          var decorate = function (job) {
            var sourceCode = job.sourceCode, basePos = job.basePos;
            /** Even entries are positions in source in ascending order.  Odd enties
              * are style markers (e.g., PR_COMMENT) that run from that position until
              * the end.
              * @type {Array.<number|string>}
              */
            var decorations = [basePos, PR_PLAIN];
            var pos = 0;  // index into sourceCode
            var tokens = sourceCode.match(tokenizer) || [];
            var styleCache = {};
      
            for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
              var token = tokens[ti];
              var style = styleCache[token];
              var match = void 0;
      
              var isEmbedded;
              if (typeof style === 'string') {
                isEmbedded = false;
              } else {
                var patternParts = shortcuts[token.charAt(0)];
                if (patternParts) {
                  match = token.match(patternParts[1]);
                  style = patternParts[0];
                } else {
                  for (var i = 0; i < nPatterns; ++i) {
                    patternParts = fallthroughStylePatterns[i];
                    match = token.match(patternParts[1]);
                    if (match) {
                      style = patternParts[0];
                      break;
                    }
                  }
      
                  if (!match) {  // make sure that we make progress
                    style = PR_PLAIN;
                  }
                }
      
                isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
                if (isEmbedded && !(match && typeof match[1] === 'string')) {
                  isEmbedded = false;
                  style = PR_SOURCE;
                }
      
                if (!isEmbedded) { styleCache[token] = style; }
              }
      
              var tokenStart = pos;
              pos += token.length;
      
              if (!isEmbedded) {
                decorations.push(basePos + tokenStart, style);
              } else {  // Treat group 1 as an embedded block of source code.
                var embeddedSource = match[1];
                var embeddedSourceStart = token.indexOf(embeddedSource);
                var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
                if (match[2]) {
                  // If embeddedSource can be blank, then it would match at the
                  // beginning which would cause us to infinitely recurse on the
                  // entire token, so we catch the right context in match[2].
                  embeddedSourceEnd = token.length - match[2].length;
                  embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
                }
                var lang = style.substring(5);
                // Decorate the left of the embedded source
                appendDecorations(
                    basePos + tokenStart,
                    token.substring(0, embeddedSourceStart),
                    decorate, decorations);
                // Decorate the embedded source
                appendDecorations(
                    basePos + tokenStart + embeddedSourceStart,
                    embeddedSource,
                    langHandlerForExtension(lang, embeddedSource),
                    decorations);
                // Decorate the right of the embedded section
                appendDecorations(
                    basePos + tokenStart + embeddedSourceEnd,
                    token.substring(embeddedSourceEnd),
                    decorate, decorations);
              }
            }
            job.decorations = decorations;
          };
          return decorate;
        }
      
        /** returns a function that produces a list of decorations from source text.
          *
          * This code treats ", ', and ` as string delimiters, and \ as a string
          * escape.  It does not recognize perl's qq() style strings.
          * It has no special handling for double delimiter escapes as in basic, or
          * the tripled delimiters used in python, but should work on those regardless
          * although in those cases a single string literal may be broken up into
          * multiple adjacent string literals.
          *
          * It recognizes C, C++, and shell style comments.
          *
          * @param {Object} options a set of optional parameters.
          * @return {function (Object)} a function that examines the source code
          *     in the input job and builds the decoration list.
          */
        function sourceDecorator(options) {
          var shortcutStylePatterns = [], fallthroughStylePatterns = [];
          if (options['tripleQuotedStrings']) {
            // '''multi-line-string''', 'single-line-string', and double-quoted
            shortcutStylePatterns.push(
                [PR_STRING,  /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
                 null, '\'"']);
          } else if (options['multiLineStrings']) {
            // 'multi-line-string', "multi-line-string"
            shortcutStylePatterns.push(
                [PR_STRING,  /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
                 null, '\'"`']);
          } else {
            // 'single-line-string', "single-line-string"
            shortcutStylePatterns.push(
                [PR_STRING,
                 /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
                 null, '"\'']);
          }
          if (options['verbatimStrings']) {
            // verbatim-string-literal production from the C# grammar.  See issue 93.
            fallthroughStylePatterns.push(
                [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
          }
          var hc = options['hashComments'];
          if (hc) {
            if (options['cStyleComments']) {
              if (hc > 1) {  // multiline hash comments
                shortcutStylePatterns.push(
                    [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
              } else {
                // Stop C preprocessor declarations at an unclosed open comment
                shortcutStylePatterns.push(
                    [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
                     null, '#']);
              }
              // #include <stdio.h>
              fallthroughStylePatterns.push(
                  [PR_STRING,
                   /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
                   null]);
            } else {
              shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
            }
          }
          if (options['cStyleComments']) {
            fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
            fallthroughStylePatterns.push(
                [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
          }
          var regexLiterals = options['regexLiterals'];
          if (regexLiterals) {
            /**
             * @const
             */
            var regexExcls = regexLiterals > 1
              ? ''  // Multiline regex literals
              : '\n\r';
            /**
             * @const
             */
            var regexAny = regexExcls ? '.' : '[\\S\\s]';
            /**
             * @const
             */
            var REGEX_LITERAL = (
                // A regular expression literal starts with a slash that is
                // not followed by * or / so that it is not confused with
                // comments.
                '/(?=[^/*' + regexExcls + '])'
                // and then contains any number of raw characters,
                + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
                // escape sequences (\x5C),
                +    '|\\x5C' + regexAny
                // or non-nesting character sets (\x5B\x5D);
                +    '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
                +             '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
                // finally closed by a /.
                + '/');
            fallthroughStylePatterns.push(
                ['lang-regex',
                 RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
                 ]);
          }
      
          var types = options['types'];
          if (types) {
            fallthroughStylePatterns.push([PR_TYPE, types]);
          }
      
          var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
          if (keywords.length) {
            fallthroughStylePatterns.push(
                [PR_KEYWORD,
                 new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
                 null]);
          }
      
          shortcutStylePatterns.push([PR_PLAIN,       /^\s+/, null, ' \r\n\t\xA0']);
      
          var punctuation =
            // The Bash man page says
      
            // A word is a sequence of characters considered as a single
            // unit by GRUB. Words are separated by metacharacters,
            // which are the following plus space, tab, and newline: { }
            // | & $ ; < >
            // ...
            
            // A word beginning with # causes that word and all remaining
            // characters on that line to be ignored.
      
            // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
            // comment but empirically
            // $ echo {#}
            // {#}
            // $ echo \$#
            // $#
            // $ echo }#
            // }#
      
            // so /(?:^|[|&;<>\s])/ is more appropriate.
      
            // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
            // suggests that this definition is compatible with a
            // default mode that tries to use a single token definition
            // to recognize both bash/python style comments and C
            // preprocessor directives.
      
            // This definition of punctuation does not include # in the list of
            // follow-on exclusions, so # will not be broken before if preceeded
            // by a punctuation character.  We could try to exclude # after
            // [|&;<>] but that doesn't seem to cause many major problems.
            // If that does turn out to be a problem, we should change the below
            // when hc is truthy to include # in the run of punctuation characters
            // only when not followint [|&;<>].
            '^.[^\\s\\w.$@\'"`/\\\\]*';
          if (options['regexLiterals']) {
            punctuation += '(?!\s*\/)';
          }
      
          fallthroughStylePatterns.push(
              // TODO(mikesamuel): recognize non-latin letters and numerals in idents
              [PR_LITERAL,     /^@[a-z_$][a-z_$@0-9]*/i, null],
              [PR_TYPE,        /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
              [PR_PLAIN,       /^[a-z_$][a-z_$@0-9]*/i, null],
              [PR_LITERAL,
               new RegExp(
                   '^(?:'
                   // A hex number
                   + '0x[a-f0-9]+'
                   // or an octal or decimal number,
                   + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
                   // possibly in scientific notation
                   + '(?:e[+\\-]?\\d+)?'
                   + ')'
                   // with an optional modifier like UL for unsigned long
                   + '[a-z]*', 'i'),
               null, '0123456789'],
              // Don't treat escaped quotes in bash as starting strings.
              // See issue 144.
              [PR_PLAIN,       /^\\[\s\S]?/, null],
              [PR_PUNCTUATION, new RegExp(punctuation), null]);
      
          return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
        }
      
        var decorateSource = sourceDecorator({
              'keywords': ALL_KEYWORDS,
              'hashComments': true,
              'cStyleComments': true,
              'multiLineStrings': true,
              'regexLiterals': true
            });
      
        include("numberLines.js");
      
        include("recombineTagsAndDecorations.js");
      
        /** Maps language-specific file extensions to handlers. */
        var langHandlerRegistry = {};
        /** Register a language handler for the given file extensions.
          * @param {function (Object)} handler a function from source code to a list
          *      of decorations.  Takes a single argument job which describes the
          *      state of the computation.   The single parameter has the form
          *      {@code {
          *        sourceCode: {string} as plain text.
          *        decorations: {Array.<number|string>} an array of style classes
          *                     preceded by the position at which they start in
          *                     job.sourceCode in order.
          *                     The language handler should assigned this field.
          *        basePos: {int} the position of source in the larger source chunk.
          *                 All positions in the output decorations array are relative
          *                 to the larger source chunk.
          *      } }
          * @param {Array.<string>} fileExtensions
          */
        function registerLangHandler(handler, fileExtensions) {
          for (var i = fileExtensions.length; --i >= 0;) {
            var ext = fileExtensions[i];
            if (!langHandlerRegistry.hasOwnProperty(ext)) {
              langHandlerRegistry[ext] = handler;
            } else if (win['console']) {
              console['warn']('cannot override language handler %s', ext);
            }
          }
        }
        function langHandlerForExtension(extension, source) {
          if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
            // Treat it as markup if the first non whitespace character is a < and
            // the last non-whitespace character is a >.
            extension = /^\s*</.test(source)
                ? 'default-markup'
                : 'default-code';
          }
          return langHandlerRegistry[extension];
        }
        registerLangHandler(decorateSource, ['default-code']);
        registerLangHandler(
            createSimpleLexer(
                [],
                [
                 [PR_PLAIN,       /^[^<?]+/],
                 [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
                 [PR_COMMENT,     /^<\!--[\s\S]*?(?:-\->|$)/],
                 // Unescaped content in an unknown language
                 ['lang-',        /^<\?([\s\S]+?)(?:\?>|$)/],
                 ['lang-',        /^<%([\s\S]+?)(?:%>|$)/],
                 [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
                 ['lang-',        /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
                 // Unescaped content in javascript.  (Or possibly vbscript).
                 ['lang-js',      /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
                 // Contains unescaped stylesheet content
                 ['lang-css',     /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
                 ['lang-in.tag',  /^(<\/?[a-z][^<>]*>)/i]
                ]),
            ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
        registerLangHandler(
            createSimpleLexer(
                [
                 [PR_PLAIN,        /^[\s]+/, null, ' \t\r\n'],
                 [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
                 ],
                [
                 [PR_TAG,          /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
                 [PR_ATTRIB_NAME,  /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
                 ['lang-uq.val',   /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
                 [PR_PUNCTUATION,  /^[=<>\/]+/],
                 ['lang-js',       /^on\w+\s*=\s*\"([^\"]+)\"/i],
                 ['lang-js',       /^on\w+\s*=\s*\'([^\']+)\'/i],
                 ['lang-js',       /^on\w+\s*=\s*([^\"\'>\s]+)/i],
                 ['lang-css',      /^style\s*=\s*\"([^\"]+)\"/i],
                 ['lang-css',      /^style\s*=\s*\'([^\']+)\'/i],
                 ['lang-css',      /^style\s*=\s*([^\"\'>\s]+)/i]
                 ]),
            ['in.tag']);
        registerLangHandler(
            createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
        registerLangHandler(sourceDecorator({
                'keywords': CPP_KEYWORDS,
                'hashComments': true,
                'cStyleComments': true,
                'types': C_TYPES
              }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
        registerLangHandler(sourceDecorator({
                'keywords': 'null,true,false'
              }), ['json']);
        registerLangHandler(sourceDecorator({
                'keywords': CSHARP_KEYWORDS,
                'hashComments': true,
                'cStyleComments': true,
                'verbatimStrings': true,
                'types': C_TYPES
              }), ['cs']);
        registerLangHandler(sourceDecorator({
                'keywords': JAVA_KEYWORDS,
                'cStyleComments': true
              }), ['java']);
        registerLangHandler(sourceDecorator({
                'keywords': SH_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true
              }), ['bash', 'bsh', 'csh', 'sh']);
        registerLangHandler(sourceDecorator({
                'keywords': PYTHON_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'tripleQuotedStrings': true
              }), ['cv', 'py', 'python']);
        registerLangHandler(sourceDecorator({
                'keywords': PERL_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'regexLiterals': 2  // multiline regex literals
              }), ['perl', 'pl', 'pm']);
        registerLangHandler(sourceDecorator({
                'keywords': RUBY_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'regexLiterals': true
              }), ['rb', 'ruby']);
        registerLangHandler(sourceDecorator({
                'keywords': JSCRIPT_KEYWORDS,
                'cStyleComments': true,
                'regexLiterals': true
              }), ['javascript', 'js']);
        registerLangHandler(sourceDecorator({
                'keywords': COFFEE_KEYWORDS,
                'hashComments': 3,  // ### style block comments
                'cStyleComments': true,
                'multilineStrings': true,
                'tripleQuotedStrings': true,
                'regexLiterals': true
              }), ['coffee']);
        registerLangHandler(sourceDecorator({
                'keywords': RUST_KEYWORDS,
                'cStyleComments': true,
                'multilineStrings': true
              }), ['rc', 'rs', 'rust']);
        registerLangHandler(
            createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
      
        function applyDecorator(job) {
          var opt_langExtension = job.langExtension;
      
          try {
            // Extract tags, and convert the source code to plain text.
            var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
            /** Plain text. @type {string} */
            var source = sourceAndSpans.sourceCode;
            job.sourceCode = source;
            job.spans = sourceAndSpans.spans;
            job.basePos = 0;
      
            // Apply the appropriate language handler
            langHandlerForExtension(opt_langExtension, source)(job);
      
            // Integrate the decorations and tags back into the source code,
            // modifying the sourceNode in place.
            recombineTagsAndDecorations(job);
          } catch (e) {
            if (win['console']) {
              console['log'](e && e['stack'] || e);
            }
          }
        }
      
        /**
         * Pretty print a chunk of code.
         * @param sourceCodeHtml {string} The HTML to pretty print.
         * @param opt_langExtension {string} The language name to use.
         *     Typically, a filename extension like 'cpp' or 'java'.
         * @param opt_numberLines {number|boolean} True to number lines,
         *     or the 1-indexed number of the first line in sourceCodeHtml.
         */
        function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
          var container = document.createElement('div');
          // This could cause images to load and onload listeners to fire.
          // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
          // We assume that the inner HTML is from a trusted source.
          // The pre-tag is required for IE8 which strips newlines from innerHTML
          // when it is injected into a <pre> tag.
          // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
          // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
          container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
          container = container.firstChild;
          if (opt_numberLines) {
            numberLines(container, opt_numberLines, true);
          }
      
          var job = {
            langExtension: opt_langExtension,
            numberLines: opt_numberLines,
            sourceNode: container,
            pre: 1
          };
          applyDecorator(job);
          return container.innerHTML;
        }
      
         /**
          * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
          * {@code class=prettyprint} and prettify them.
          *
          * @param {Function} opt_whenDone called when prettifying is done.
          * @param {HTMLElement|HTMLDocument} opt_root an element or document
          *   containing all the elements to pretty print.
          *   Defaults to {@code document.body}.
          */
        function $prettyPrint(opt_whenDone, opt_root) {
          var root = opt_root || document.body;
          var doc = root.ownerDocument || document;
          function byTagName(tn) { return root.getElementsByTagName(tn); }
          // fetch a list of nodes to rewrite
          var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
          var elements = [];
          for (var i = 0; i < codeSegments.length; ++i) {
            for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
              elements.push(codeSegments[i][j]);
            }
          }
          codeSegments = null;
      
          var clock = Date;
          if (!clock['now']) {
            clock = { 'now': function () { return +(new Date); } };
          }
      
          // The loop is broken into a series of continuations to make sure that we
          // don't make the browser unresponsive when rewriting a large page.
          var k = 0;
          var prettyPrintingJob;
      
          var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
          var prettyPrintRe = /\bprettyprint\b/;
          var prettyPrintedRe = /\bprettyprinted\b/;
          var preformattedTagNameRe = /pre|xmp/i;
          var codeRe = /^code$/i;
          var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
          var EMPTY = {};
      
          function doWork() {
            var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
                           clock['now']() + 250 /* ms */ :
                           Infinity);
            for (; k < elements.length && clock['now']() < endTime; k++) {
              var cs = elements[k];
      
              // Look for a preceding comment like
              // <?prettify lang="..." linenums="..."?>
              var attrs = EMPTY;
              {
                for (var preceder = cs; (preceder = preceder.previousSibling);) {
                  var nt = preceder.nodeType;
                  // <?foo?> is parsed by HTML 5 to a comment node (8)
                  // like <!--?foo?-->, but in XML is a processing instruction
                  var value = (nt === 7 || nt === 8) && preceder.nodeValue;
                  if (value
                      ? !/^\??prettify\b/.test(value)
                      : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
                    // Skip over white-space text nodes but not others.
                    break;
                  }
                  if (value) {
                    attrs = {};
                    value.replace(
                        /\b(\w+)=([\w:.%+-]+)/g,
                      function (_, name, value) { attrs[name] = value; });
                    break;
                  }
                }
              }
      
              var className = cs.className;
              if ((attrs !== EMPTY || prettyPrintRe.test(className))
                  // Don't redo this if we've already done it.
                  // This allows recalling pretty print to just prettyprint elements
                  // that have been added to the page since last call.
                  && !prettyPrintedRe.test(className)) {
      
                // make sure this is not nested in an already prettified element
                var nested = false;
                for (var p = cs.parentNode; p; p = p.parentNode) {
                  var tn = p.tagName;
                  if (preCodeXmpRe.test(tn)
                      && p.className && prettyPrintRe.test(p.className)) {
                    nested = true;
                    break;
                  }
                }
                if (!nested) {
                  // Mark done.  If we fail to prettyprint for whatever reason,
                  // we shouldn't try again.
                  cs.className += ' prettyprinted';
      
                  // If the classes includes a language extensions, use it.
                  // Language extensions can be specified like
                  //     <pre class="prettyprint lang-cpp">
                  // the language extension "cpp" is used to find a language handler
                  // as passed to PR.registerLangHandler.
                  // HTML5 recommends that a language be specified using "language-"
                  // as the prefix instead.  Google Code Prettify supports both.
                  // http://dev.w3.org/html5/spec-author-view/the-code-element.html
                  var langExtension = attrs['lang'];
                  if (!langExtension) {
                    langExtension = className.match(langExtensionRe);
                    // Support <pre class="prettyprint"><code class="language-c">
                    var wrapper;
                    if (!langExtension && (wrapper = childContentWrapper(cs))
                        && codeRe.test(wrapper.tagName)) {
                      langExtension = wrapper.className.match(langExtensionRe);
                    }
      
                    if (langExtension) { langExtension = langExtension[1]; }
                  }
      
                  var preformatted;
                  if (preformattedTagNameRe.test(cs.tagName)) {
                    preformatted = 1;
                  } else {
                    var currentStyle = cs['currentStyle'];
                    var defaultView = doc.defaultView;
                    var whitespace = (
                        currentStyle
                        ? currentStyle['whiteSpace']
                        : (defaultView
                           && defaultView.getComputedStyle)
                        ? defaultView.getComputedStyle(cs, null)
                        .getPropertyValue('white-space')
                        : 0);
                    preformatted = whitespace
                        && 'pre' === whitespace.substring(0, 3);
                  }
      
                  // Look for a class like linenums or linenums:<n> where <n> is the
                  // 1-indexed number of the first line.
                  var lineNums = attrs['linenums'];
                  if (!(lineNums = lineNums === 'true' || +lineNums)) {
                    lineNums = className.match(/\blinenums\b(?::(\d+))?/);
                    lineNums =
                      lineNums
                      ? lineNums[1] && lineNums[1].length
                        ? +lineNums[1] : true
                      : false;
                  }
                  if (lineNums) { numberLines(cs, lineNums, preformatted); }
      
                  // do the pretty printing
                  prettyPrintingJob = {
                    langExtension: langExtension,
                    sourceNode: cs,
                    numberLines: lineNums,
                    pre: preformatted
                  };
                  applyDecorator(prettyPrintingJob);
                }
              }
            }
            if (k < elements.length) {
              // finish up in a continuation
              setTimeout(doWork, 250);
            } else if ('function' === typeof opt_whenDone) {
              opt_whenDone();
            }
          }
      
          doWork();
        }
      
        /**
         * Contains functions for creating and registering new language handlers.
         * @type {Object}
         */
        var PR = win['PR'] = {
              'createSimpleLexer': createSimpleLexer,
              'registerLangHandler': registerLangHandler,
              'sourceDecorator': sourceDecorator,
              'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
              'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
              'PR_COMMENT': PR_COMMENT,
              'PR_DECLARATION': PR_DECLARATION,
              'PR_KEYWORD': PR_KEYWORD,
              'PR_LITERAL': PR_LITERAL,
              'PR_NOCODE': PR_NOCODE,
              'PR_PLAIN': PR_PLAIN,
              'PR_PUNCTUATION': PR_PUNCTUATION,
              'PR_SOURCE': PR_SOURCE,
              'PR_STRING': PR_STRING,
              'PR_TAG': PR_TAG,
              'PR_TYPE': PR_TYPE,
              'prettyPrintOne':
                 IN_GLOBAL_SCOPE
                   ? (win['prettyPrintOne'] = $prettyPrintOne)
                   : (prettyPrintOne = $prettyPrintOne),
              'prettyPrint': prettyPrint =
                 IN_GLOBAL_SCOPE
                   ? (win['prettyPrint'] = $prettyPrint)
                   : (prettyPrint = $prettyPrint)
            };
      
        // Make PR available via the Asynchronous Module Definition (AMD) API.
        // Per https://github.com/amdjs/amdjs-api/wiki/AMD:
        // The Asynchronous Module Definition (AMD) API specifies a
        // mechanism for defining modules such that the module and its
        // dependencies can be asynchronously loaded.
        // ...
        // To allow a clear indicator that a global define function (as
        // needed for script src browser loading) conforms to the AMD API,
        // any global define function SHOULD have a property called "amd"
        // whose value is an object. This helps avoid conflict with any
        // other existing JavaScript code that could have defined a define()
        // function that does not conform to the AMD API.
        if (typeof define === "function" && define['amd']) {
          define("google-code-prettify", [], function () {
            return PR; 
          });
        }
      })();
      ������������������������������������������������������������prettify-2013.03.04/js-modules/js_include.pl��������������������������������������������������������0000640�0001750�0001750�00000004370�12115200050�017134� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/perl
      
      # Given a JS file looks for lines like
      #    include("path/to/file/to/include");
      # and replaces them with the quoted file relative to the js-modules directory.
      # If the included file ends with ".pl" then it is treated as a perl file to
      # execute and the stdout is used as the JS to include.
      
      use strict;
      
      # Closure Compiler @define annotations that need to be pulled out of included
      # files because @defines need to be top-level vars.
      my $global_defs = "";
      
      # Find @defines at the top of a JS file by pulling off comments and looking for
      # comments containing @define followed by a var declaration.
      sub extractGlobalDefs($) {
        my @headerComments;
        my $s = shift;
        while ($s) {
          last unless $s =~ m#^\s*(?://[^\r\n]*|/\*.*?\*/[ \t]*)[\r\n]*#s;
          my $comment = $&;
          $s = $';
          if ($comment =~ /[\@]define/ && $s =~ /^\s*var\s+[^;]+;[ \t]*[\r\n]*/) {
            my $global = $&;
            $s = $';
            $global =~ s/(var\s*IN_GLOBAL_SCOPE\s*=\s*)true\b/$1false/;
            $global_defs .= "$comment$global";
          } else {
            push(@headerComments, $comment);
          }
        }
        return (join "", @headerComments) . $s;
      }
      
      # readInclude(whiteSpacePrefix, path) returns the JS content at path
      # (with the ".pl" adjustment above) and prepends each line with the
      # whitespace in whiteSpacePrefix to produce a chunk of JS that matches the
      # indentation of the including file.
      # @defines are extracted so that they can all appear globally at the top of
      # the file.
      sub readInclude($$) {
        my $prefix = shift;
        my $name = "js-modules/" . (shift);
        my $in;
        if ($name =~ /\.pl$/) {
          open($in, "perl $name|") or die "$name: $!";
        } else {
          open($in, "<$name")      or die "$name: $!";
        }
        my $buf = "";
        while (<$in>) {
          if (m/(\s*)include\("([^"]+)"\);\s*$/) {
            my $inc = extractGlobalDefs(readInclude("$prefix$1", $2));
            $buf .= $inc;
          } else {
            $buf .= "$prefix$_";
          }
        }
        close($in);
        return $buf;
      }
      
      my $target = shift;
      my $inc = readInclude("", $target);
      my $header = "";
      # Put descriptive top level comments above the grouped @defines.
      if ($inc =~ s#^(?://[^\r\n]*|/\*.*?\*/|\s)+##s) {
        $header = $&;
      }
      my $globals = $global_defs;
      # Un-indent @defines.
      $globals =~ s#^[ \t]*##gm;
      $globals .= "\n" unless $globals eq "";
      
      print "$header$globals$inc";
      ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/numberLines.js�������������������������������������������������������0000640�0001750�0001750�00000011072�12115200050�017276� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/**
       * Given a DOM subtree, wraps it in a list, and puts each line into its own
       * list item.
       *
       * @param {Node} node modified in place.  Its content is pulled into an
       *     HTMLOListElement, and each line is moved into a separate list item.
       *     This requires cloning elements, so the input might not have unique
       *     IDs after numbering.
       * @param {boolean} isPreformatted true iff white-space in text nodes should
       *     be treated as significant.
       */
      function numberLines(node, opt_startLineNum, isPreformatted) {
        var nocode = /(?:^|\s)nocode(?:\s|$)/;
        var lineBreak = /\r\n?|\n/;
      
        var document = node.ownerDocument;
      
        var li = document.createElement('li');
        while (node.firstChild) {
          li.appendChild(node.firstChild);
        }
        // An array of lines.  We split below, so this is initialized to one
        // un-split line.
        var listItems = [li];
      
        function walk(node) {
          var type = node.nodeType;
          if (type == 1 && !nocode.test(node.className)) {  // Element
            if ('br' === node.nodeName) {
              breakAfter(node);
              // Discard the <BR> since it is now flush against a </LI>.
              if (node.parentNode) {
                node.parentNode.removeChild(node);
              }
            } else {
              for (var child = node.firstChild; child; child = child.nextSibling) {
                walk(child);
              }
            }
          } else if ((type == 3 || type == 4) && isPreformatted) {  // Text
            var text = node.nodeValue;
            var match = text.match(lineBreak);
            if (match) {
              var firstLine = text.substring(0, match.index);
              node.nodeValue = firstLine;
              var tail = text.substring(match.index + match[0].length);
              if (tail) {
                var parent = node.parentNode;
                parent.insertBefore(
                  document.createTextNode(tail), node.nextSibling);
              }
              breakAfter(node);
              if (!firstLine) {
                // Don't leave blank text nodes in the DOM.
                node.parentNode.removeChild(node);
              }
            }
          }
        }
      
        // Split a line after the given node.
        function breakAfter(lineEndNode) {
          // If there's nothing to the right, then we can skip ending the line
          // here, and move root-wards since splitting just before an end-tag
          // would require us to create a bunch of empty copies.
          while (!lineEndNode.nextSibling) {
            lineEndNode = lineEndNode.parentNode;
            if (!lineEndNode) { return; }
          }
      
          function breakLeftOf(limit, copy) {
            // Clone shallowly if this node needs to be on both sides of the break.
            var rightSide = copy ? limit.cloneNode(false) : limit;
            var parent = limit.parentNode;
            if (parent) {
              // We clone the parent chain.
              // This helps us resurrect important styling elements that cross lines.
              // E.g. in <i>Foo<br>Bar</i>
              // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
              var parentClone = breakLeftOf(parent, 1);
              // Move the clone and everything to the right of the original
              // onto the cloned parent.
              var next = limit.nextSibling;
              parentClone.appendChild(rightSide);
              for (var sibling = next; sibling; sibling = next) {
                next = sibling.nextSibling;
                parentClone.appendChild(sibling);
              }
            }
            return rightSide;
          }
      
          var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
      
          // Walk the parent chain until we reach an unattached LI.
          for (var parent;
               // Check nodeType since IE invents document fragments.
               (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
            copiedListItem = parent;
          }
          // Put it on the list of lines for later processing.
          listItems.push(copiedListItem);
        }
      
        // Split lines while there are lines left to split.
        for (var i = 0;  // Number of lines that have been split so far.
             i < listItems.length;  // length updated by breakAfter calls.
             ++i) {
          walk(listItems[i]);
        }
      
        // Make sure numeric indices show correctly.
        if (opt_startLineNum === (opt_startLineNum|0)) {
          listItems[0].setAttribute('value', opt_startLineNum);
        }
      
        var ol = document.createElement('ol');
        ol.className = 'linenums';
        var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
        for (var i = 0, n = listItems.length; i < n; ++i) {
          li = listItems[i];
          // Stick a class on the LIs so that stylesheets can
          // color odd/even rows, or any other row pattern that
          // is co-prime with 10.
          li.className = 'L' + ((i + offset) % 10);
          if (!li.firstChild) {
            li.appendChild(document.createTextNode('\xA0'));
          }
          ol.appendChild(li);
        }
      
        node.appendChild(ol);
      }����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/combinePrefixPatterns.js���������������������������������������������0000640�0001750�0001750�00000017444�12115200050�021337� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/**
       * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
       * matches the union of the sets of strings matched by the input RegExp.
       * Since it matches globally, if the input strings have a start-of-input
       * anchor (/^.../), it is ignored for the purposes of unioning.
       * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
       * @return {RegExp} a global regex.
       */
      function combinePrefixPatterns(regexs) {
        var capturedGroupIndex = 0;
      
        var needToFoldCase = false;
        var ignoreCase = false;
        for (var i = 0, n = regexs.length; i < n; ++i) {
          var regex = regexs[i];
          if (regex.ignoreCase) {
            ignoreCase = true;
          } else if (/[a-z]/i.test(regex.source.replace(
                         /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
            needToFoldCase = true;
            ignoreCase = false;
            break;
          }
        }
      
        var escapeCharToCodeUnit = {
          'b': 8,
          't': 9,
          'n': 0xa,
          'v': 0xb,
          'f': 0xc,
          'r': 0xd
        };
      
        function decodeEscape(charsetPart) {
          var cc0 = charsetPart.charCodeAt(0);
          if (cc0 !== 92 /* \\ */) {
            return cc0;
          }
          var c1 = charsetPart.charAt(1);
          cc0 = escapeCharToCodeUnit[c1];
          if (cc0) {
            return cc0;
          } else if ('0' <= c1 && c1 <= '7') {
            return parseInt(charsetPart.substring(1), 8);
          } else if (c1 === 'u' || c1 === 'x') {
            return parseInt(charsetPart.substring(2), 16);
          } else {
            return charsetPart.charCodeAt(1);
          }
        }
      
        function encodeEscape(charCode) {
          if (charCode < 0x20) {
            return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
          }
          var ch = String.fromCharCode(charCode);
          return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
              ? "\\" + ch : ch;
        }
      
        function caseFoldCharset(charSet) {
          var charsetParts = charSet.substring(1, charSet.length - 1).match(
              new RegExp(
                  '\\\\u[0-9A-Fa-f]{4}'
                  + '|\\\\x[0-9A-Fa-f]{2}'
                  + '|\\\\[0-3][0-7]{0,2}'
                  + '|\\\\[0-7]{1,2}'
                  + '|\\\\[\\s\\S]'
                  + '|-'
                  + '|[^-\\\\]',
                  'g'));
          var ranges = [];
          var inverse = charsetParts[0] === '^';
      
          var out = ['['];
          if (inverse) { out.push('^'); }
      
          for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
            var p = charsetParts[i];
            if (/\\[bdsw]/i.test(p)) {  // Don't muck with named groups.
              out.push(p);
            } else {
              var start = decodeEscape(p);
              var end;
              if (i + 2 < n && '-' === charsetParts[i + 1]) {
                end = decodeEscape(charsetParts[i + 2]);
                i += 2;
              } else {
                end = start;
              }
              ranges.push([start, end]);
              // If the range might intersect letters, then expand it.
              // This case handling is too simplistic.
              // It does not deal with non-latin case folding.
              // It works for latin source code identifiers though.
              if (!(end < 65 || start > 122)) {
                if (!(end < 65 || start > 90)) {
                  ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
                }
                if (!(end < 97 || start > 122)) {
                  ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
                }
              }
            }
          }
      
          // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
          // -> [[1, 12], [14, 14], [16, 17]]
          ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1]  - a[1]); });
          var consolidatedRanges = [];
          var lastRange = [];
          for (var i = 0; i < ranges.length; ++i) {
            var range = ranges[i];
            if (range[0] <= lastRange[1] + 1) {
              lastRange[1] = Math.max(lastRange[1], range[1]);
            } else {
              consolidatedRanges.push(lastRange = range);
            }
          }
      
          for (var i = 0; i < consolidatedRanges.length; ++i) {
            var range = consolidatedRanges[i];
            out.push(encodeEscape(range[0]));
            if (range[1] > range[0]) {
              if (range[1] + 1 > range[0]) { out.push('-'); }
              out.push(encodeEscape(range[1]));
            }
          }
          out.push(']');
          return out.join('');
        }
      
        function allowAnywhereFoldCaseAndRenumberGroups(regex) {
          // Split into character sets, escape sequences, punctuation strings
          // like ('(', '(?:', ')', '^'), and runs of characters that do not
          // include any of the above.
          var parts = regex.source.match(
              new RegExp(
                  '(?:'
                  + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]'  // a character set
                  + '|\\\\u[A-Fa-f0-9]{4}'  // a unicode escape
                  + '|\\\\x[A-Fa-f0-9]{2}'  // a hex escape
                  + '|\\\\[0-9]+'  // a back-reference or octal escape
                  + '|\\\\[^ux0-9]'  // other escape sequence
                  + '|\\(\\?[:!=]'  // start of a non-capturing group
                  + '|[\\(\\)\\^]'  // start/end of a group, or line start
                  + '|[^\\x5B\\x5C\\(\\)\\^]+'  // run of other characters
                  + ')',
                  'g'));
          var n = parts.length;
      
          // Maps captured group numbers to the number they will occupy in
          // the output or to -1 if that has not been determined, or to
          // undefined if they need not be capturing in the output.
          var capturedGroups = [];
      
          // Walk over and identify back references to build the capturedGroups
          // mapping.
          for (var i = 0, groupIndex = 0; i < n; ++i) {
            var p = parts[i];
            if (p === '(') {
              // groups are 1-indexed, so max group index is count of '('
              ++groupIndex;
            } else if ('\\' === p.charAt(0)) {
              var decimalValue = +p.substring(1);
              if (decimalValue) {
                if (decimalValue <= groupIndex) {
                  capturedGroups[decimalValue] = -1;
                } else {
                  // Replace with an unambiguous escape sequence so that
                  // an octal escape sequence does not turn into a backreference
                  // to a capturing group from an earlier regex.
                  parts[i] = encodeEscape(decimalValue);
                }
              }
            }
          }
      
          // Renumber groups and reduce capturing groups to non-capturing groups
          // where possible.
          for (var i = 1; i < capturedGroups.length; ++i) {
            if (-1 === capturedGroups[i]) {
              capturedGroups[i] = ++capturedGroupIndex;
            }
          }
          for (var i = 0, groupIndex = 0; i < n; ++i) {
            var p = parts[i];
            if (p === '(') {
              ++groupIndex;
              if (!capturedGroups[groupIndex]) {
                parts[i] = '(?:';
              }
            } else if ('\\' === p.charAt(0)) {
              var decimalValue = +p.substring(1);
              if (decimalValue && decimalValue <= groupIndex) {
                parts[i] = '\\' + capturedGroups[decimalValue];
              }
            }
          }
      
          // Remove any prefix anchors so that the output will match anywhere.
          // ^^ really does mean an anchored match though.
          for (var i = 0; i < n; ++i) {
            if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
          }
      
          // Expand letters to groups to handle mixing of case-sensitive and
          // case-insensitive patterns if necessary.
          if (regex.ignoreCase && needToFoldCase) {
            for (var i = 0; i < n; ++i) {
              var p = parts[i];
              var ch0 = p.charAt(0);
              if (p.length >= 2 && ch0 === '[') {
                parts[i] = caseFoldCharset(p);
              } else if (ch0 !== '\\') {
                // TODO: handle letters in numeric escapes.
                parts[i] = p.replace(
                    /[a-zA-Z]/g,
                    function (ch) {
                      var cc = ch.charCodeAt(0);
                      return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
                    });
              }
            }
          }
      
          return parts.join('');
        }
      
        var rewritten = [];
        for (var i = 0, n = regexs.length; i < n; ++i) {
          var regex = regexs[i];
          if (regex.global || regex.multiline) { throw new Error('' + regex); }
          rewritten.push(
              '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
        }
      
        return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
      }
      ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/extractSourceSpans.js������������������������������������������������0000640�0001750�0001750�00000005022�12115200050�020651� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/**
       * Split markup into a string of source code and an array mapping ranges in
       * that string to the text nodes in which they appear.
       *
       * <p>
       * The HTML DOM structure:</p>
       * <pre>
       * (Element   "p"
       *   (Element "b"
       *     (Text  "print "))       ; #1
       *   (Text    "'Hello '")      ; #2
       *   (Element "br")            ; #3
       *   (Text    "  + 'World';")) ; #4
       * </pre>
       * <p>
       * corresponds to the HTML
       * {@code <p><b>print </b>'Hello '<br>  + 'World';</p>}.</p>
       *
       * <p>
       * It will produce the output:</p>
       * <pre>
       * {
       *   sourceCode: "print 'Hello '\n  + 'World';",
       *   //                     1          2
       *   //           012345678901234 5678901234567
       *   spans: [0, #1, 6, #2, 14, #3, 15, #4]
       * }
       * </pre>
       * <p>
       * where #1 is a reference to the {@code "print "} text node above, and so
       * on for the other text nodes.
       * </p>
       *
       * <p>
       * The {@code} spans array is an array of pairs.  Even elements are the start
       * indices of substrings, and odd elements are the text nodes (or BR elements)
       * that contain the text for those substrings.
       * Substrings continue until the next index or the end of the source.
       * </p>
       *
       * @param {Node} node an HTML DOM subtree containing source-code.
       * @param {boolean} isPreformatted true if white-space in text nodes should
       *    be considered significant.
       * @return {Object} source code and the text nodes in which they occur.
       */
      function extractSourceSpans(node, isPreformatted) {
        var nocode = /(?:^|\s)nocode(?:\s|$)/;
      
        var chunks = [];
        var length = 0;
        var spans = [];
        var k = 0;
      
        function walk(node) {
          var type = node.nodeType;
          if (type == 1) {  // Element
            if (nocode.test(node.className)) { return; }
            for (var child = node.firstChild; child; child = child.nextSibling) {
              walk(child);
            }
            var nodeName = node.nodeName.toLowerCase();
            if ('br' === nodeName || 'li' === nodeName) {
              chunks[k] = '\n';
              spans[k << 1] = length++;
              spans[(k++ << 1) | 1] = node;
            }
          } else if (type == 3 || type == 4) {  // Text
            var text = node.nodeValue;
            if (text.length) {
              if (!isPreformatted) {
                text = text.replace(/[ \t\r\n]+/g, ' ');
              } else {
                text = text.replace(/\r\n?/g, '\n');  // Normalize newlines.
              }
              // TODO: handle tabs here?
              chunks[k] = text;
              spans[k << 1] = length;
              length += text.length;
              spans[(k++ << 1) | 1] = node;
            }
          }
        }
      
        walk(node);
      
        return {
          sourceCode: chunks.join('').replace(/\n$/, ''),
          spans: spans
        };
      }
      ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/numberLines_test.html������������������������������������������������0000640�0001750�0001750�00000011165�12115200050�020670� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
      <html> <head>
      <title>Number Lines Test</title>
      <script src="numberLines.js"></script>
      <script src="http://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
      <style>
      .ok { background: #dfd }
      .error, .failure { background: #fdd }
      td { font-family: monospace }
      tr { vertical-align: top }
      </style>
      </head>
      
      <body>
      <h1>Number Lines Test</h1>
      
      <table>
        <tr><th colspan=3>Test Nothing to Split</th></tr>
        <tr>
          <td><code class="testinput">Hello, World!</code></td>
          <td><code><ol class="linenums"><li class="L0">Hello, World!</li></ol></code></td>
        </tr>
        <tr><th colspan=3>Test Normalized Spaces</th></tr>
        <tr>
          <td><code class="testinput">Hello,&#10;World!</code></td>
          <td><code><ol class="linenums"><li class="L0">Hello,&#10;World!</li></ol></code></td>
        </tr>
        <tr><th colspan=3>Test BR</th></tr>
        <tr>
          <td><pre class="testinput">Hello,<br>World!</pre></td>
          <td><pre><ol class="linenums"><li class="L0">Hello,</li><li class="L1">World!</li></ol></pre></td>
        </tr>
        <tr><th colspan=3>Test line breaks</th></tr>
        <tr>
          <td><pre class="testinput">Hello,&#10;there&#10;World!</pre></td>
          <td><pre><ol class="linenums"><li class="L0">Hello,</li><li class="L1">there</li><li class="L2">World!</li></ol></pre></td>
        </tr>
        <tr><th colspan=3>Test line breaks with followers</th></tr>
        <tr>
          <td><pre class="testinput"><b>Hello,&#10;there&#10;World!&#10;</b><button>OK</button></pre></td>
          <td><pre><ol class="linenums"><li class="L0"><b>Hello,</b></li><li class="L1"><b>there</b></li><li class="L2"><b>World!</b></li><li class="L3"><button>OK</button></ol></pre></td>
        </tr>
        <tr><th colspan=3>Test nocode</th></tr>
        <tr>
          <td><pre class="testinput">Hello,&#10;the<span class="nocode">re&#10;World!</span></pre></td>
          <td><pre><ol class="linenums"><li class="L0">Hello,</li><li class="L1">the<span class="nocode">re&#10;World!</span></li></ol></pre></td>
        </tr>
        <tr><th colspan=3>Test link</th></tr>
        <tr>
          <td><pre class="testinput">Hello,&#10;the<a href="#" style="font-weight: bold">re&#10;Wor</a>ld!</pre></td>
          <td><pre><ol class="linenums"><li class="L0">Hello,</li><li class="L1">the<a href="#" style="font-weight: bold">re</a></li><li class="L2"><a href="#" style="font-weight: bold">Wor</a>ld!</li></ol></pre></td>
        </tr>
        <tr><th colspan=3>Test blank lines</th></tr>
        <tr>
          <td><pre class="testinput">One&#10;&#10;Three</pre></td>
          <td><pre><ol class="linenums"><li class="L0">One</li><li class="L1">&nbsp;</li><li class="L2">Three</li></ol></pre></td>
        </tr>
      </table>
      
      <script>
      if (!document.body.getElementsByClassName) {
        document.body.getElementsByClassName = function (className) {
          className = className.replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ' ');
          var results = [];
          function walk(node) {
            if (node.nodeType !== 1) { return; }
            // This test should be order-insensitive.
            if ((' ' + node.className + ' ').indexOf(className) >= 0) {
              results[results.length] = node;
            }
            for (var child = node.firstChild; child; child = child.nextSibling) {
              walk(child);
            }
          }
          walk(document.body);
          return results;
        };
      }
      
      setTimeout(function () {
        function normListItems(html) {
          // IE likes to leave out </li>s before <li>s.
          return html.replace(/<\/li>(<li\b)/gi, '$1');
        }
      
        var testInputs = Array.prototype.slice.call(
           document.body.getElementsByClassName('testinput'), 0);
        for (var i = 0, n = testInputs.length; i < n; ++i) {
          var testInput = testInputs[i];
          var testResult = testInput.parentNode.nextSibling;
          while (testResult.nodeType !== 1) { testResult = testResult.nextSibling; }
          var actual = document.createElement('TD');
          testResult.parentNode.appendChild(actual);
          try {
            var testInputClone = testInput.cloneNode(true);
            testInputClone.className = '';  // IE
            testInputClone.removeAttribute('class');  // Not IE.
            actual.appendChild(testInputClone);
            numberLines(testInputClone);
            var goldenNorm = normListItems(testResult.innerHTML);
            var actualNorm = normListItems(actual.innerHTML);
            var passed = goldenNorm === actualNorm;
            if (!passed) {
              console.log(JSON.stringify(goldenNorm)
                          + ' !==\n' + JSON.stringify(actualNorm));
            }
            actual.className = passed ? 'ok' : 'failure';
          } catch (ex) {
            actual.className = 'error';
            actual.appendChild(document.createTextNode('Error: ' + (ex.message || ex)));
          }
          actual.className += ' actual';
        }
      }, 0)</script>
      
      <hr>
      <address></address>
      <!-- hhmts start --> Last modified: Tue Mar 29 16:44:05 PDT 2011 <!-- hhmts end -->
      </body> </html>
      �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������prettify-2013.03.04/js-modules/regexpPrecederPatterns.pl��������������������������������������������0000640�0001750�0001750�00000005042�12115200050�021477� 0����������������������������������������������������������������������������������������������������ustar  �domi����������������������������domi�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������use strict;
      
      print "
      
      /**
       * A set of tokens that can precede a regular expression literal in
       * javascript
       * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
       * has the full list, but I've removed ones that might be problematic when
       * seen in languages that don't support regular expression literals.
       *
       * <p>Specifically, I've removed any keywords that can't precede a regexp
       * literal in a syntactically legal javascript program, and I've removed the
       * \"in\" keyword since it's not a keyword in many languages, and might be used
       * as a count of inches.
       *
       * <p>The link above does not accurately describe EcmaScript rules since
       * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
       * very well in practice.
       *
       * \@private
       * \@const
       */
      var REGEXP_PRECEDER_PATTERN = ";
      
      my @preceders = (
                       "[!=]=?=?",   # "!", "!=", "!==", "=", "==", "===",
                       "\\#",
                       "%=?",        # "%", "%=",
                       "&&?=?",      # "&", "&&", "&&=", "&=",
                       "\\(",
                       "\\*=?",      # "*", "*=",
                       "[+\\-]=",    # +=, -=.  + and - handled below.
                       "->",
                       "\\/=?",      # "/", "/=",
                       "::?",        # ":", "::",
                       "<<?=?",      # "<", "<<", "<<=", "<=", 
                       ">>?>?=?",    # ">", ">=", ">>", ">>=", ">>>", ">>>=",
                       ",",
                       ";",          # ";"
                       "\\?",
                       "@",
                       "\\[",
                       "~",          # handles =~ and !~
                       "{",
                       "\\^\\^?=?",  # "^", "^=", "^^", "^^=",
                       "\\|\\|?=?",  # "|", "|=", "||", "||=",
                       "break", "case", "continue", "delete",
                       "do", "else", "finally", "instanceof",
                       "return", "throw", "try", "typeof"
                      );
      # match at beginning, a dot that is not part of a number, or sign.
      my $pattern = "'(?:^^\\\\.?|[+-]";
      foreach my $preceder (@preceders) {
        $preceder =~ s/\\/\\\\/g;
        $pattern .= "|$preceder";
      }
      $pattern .= ")\\\\s*'";  # matches at end, and matches empty string
      
      print "$pattern;\n";
      
      print "
      // CAVEAT: this does not properly handle the case where a regular
      // expression immediately follows another since a regular expression may
      // have flags for case-sensitivity and the like.  Having regexp tokens
      // adjacent is not valid in any language I'm aware of, so I'm punting.
      // TODO: maybe style special characters inside a regexp as punctuation.
      ";
      ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������