prettify-2013.03.04/ 0000751 0001750 0001750 00000000000 12362771374 012424 5 ustar domi domi prettify-2013.03.04/examples/ 0000751 0001750 0001750 00000000000 12362767251 014241 5 ustar domi domi prettify-2013.03.04/examples/quine.html 0000640 0001750 0001750 00000003544 12115200050 016225 0 ustar domi domi
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.
<code> elements with newlines in the text
which use CSS to specify white-space:pre will have the newlines
improperly stripped if the element is not attached to the document at the time
the stripping is done. Also, on IE 6, all newlines will be stripped from
<code> elements because of the way IE6 produces
innerHTML. Workaround: use <pre> for code with
newlines.
prettyPrintOne was not halting. This was not
reachable through the normal entry point.
is no longer applicable.Caveats: please properly escape less-thans. x<y instead of x<y, and use " instead of " for string delimiters.
lang-<language-file-extension>'''string'''
/ in regex [charsets] should not end regex
nocode spans to allow embedding of line
numbers and code annotations which should not be styled or otherwise
affect the tokenization of prettified code.
See the issue 22
testcase.
<code> blocks with embedded newlines.
  instead of
so that the output works when embedded in XML.
Bug
108.prettyPrintOne injects the HTML
passed to it into a <pre> element.
If the HTML comes from a trusted source, this may allow XSS.
Do not do this. This should not be a problem for existing apps
since the standard usage is to rewrite the HTML and then inject
it, so anyone doing that with untrusted HTML already has an XSS
vulnerability. If you sanitize and prettify HTML from an
untrusted source, sanitize first.
>script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js></script>
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. } |
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:
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.
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.
...Yes. Prettifying obfuscated code is like putting lipstick on a pig — i.e. outside the scope of this tool.
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.
See the change log
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.
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();
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.
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.
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.
Instead of <pre class="prettyprint ..."> you can use a
comment or processing instructions that survives processing instructions :
<?prettify ...?> works as explained in
Getting Started
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>
(: -------- :)
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"));
% 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}
#! /bin/bash # toascii.sh for i in $(echo $* | fold -w 1);do printf "%x " \'$i; done; echo
<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 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)
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
The language is attached to a CODE element inside a PRE.
; foo
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
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
"No tag backs."
- "No tag backs."
static Persistent<String> listeners_symbol;
(* 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;
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
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";
}
#!/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
}
### 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
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
; 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}
if(!/^https?:\/\//i.test(val) && foo == 'bar') {
val = 'http://' + val;
}
%%%%%%%%%%%%%%%%%% 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.html 0000640 0001750 0001750 00000343743 12115200050 017345 0 ustar domi domi
#!/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
#!/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
# Comment
local $x = ${#x[@]} # Previous is not a comment
# A comment
#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));
}
#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 */
#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);
}
#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);
}
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()));
}
}
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
/**
* 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));
/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/;
/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/;
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
#!/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);
#!/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)
#!/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 */
/* 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);
<!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>
<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>
…
</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>
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>
…
</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>
<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>
<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>
<!-- Test elements and attributes with namespaces -->
<xsl:stylesheet xml:lang="en">
<xsl:template match=".">
<xsl:text>Hello World</xsl:text>
</xsl:template>
</xsl:stylesheet>
// ends with line comment token //
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.
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 |
<br> as newline//comment
int main(int argc, char **argv) {}
<!-- There's an HTML comment in my comment --> <p>And another one inside the end tag</p>
<html> <head>
<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.
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: }
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
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)
-- 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)
(*
* 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.
; -*- 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))
throw new RuntimeException("Element [" + element.getName() +
"] missing attribute.");
variable++;
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];
}
#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>
}}}
<!--
@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}
-->
<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>
super(" ");
#One
Two words
#One
Two lines
#One Two lines
#One
Two lines
#One
Two lines
<?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>
// The normal string syntax string a = "C:\\"; // is equivalent to a verbatim string string b = @"C:\";
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;
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"
}
/* 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()
}
}
}
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 /* ` /*/ */
% 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.js 0000640 0001750 0001750 00000017705 12115200050 016055 0 ustar domi domi // 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('\none short line,
one giant leap for
cross-browser compatibility
two turtledoves
a partridge in a pear tree
zero fencepost errors
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.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
one two three
<div style="color: #f00"> Hello, World! </div>prettify-2013.03.04/src/ 0000751 0001750 0001750 00000000000 12362767251 013212 5 ustar domi domi prettify-2013.03.04/src/lang-css.js 0000640 0001750 0001750 00000014047 12115200050 015234 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 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', /} *
} 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.
*
* 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 } or {@code } element to specify the
* language, as in {@code }. 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.
*
* Change log:
* cbeust, 2006/08/22
*
* Java annotations (start with "@") are now captured as literals ("lit")
*
* @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 } and {@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.
*
* 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.
*
*
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.} 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.
*
*
* The HTML DOM structure:
*
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
*
*
* corresponds to the HTML
* {@code
print 'Hello '
+ 'World';
}.
*
*
* It will produce the output:
*
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
*
*
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
*
*
*
* 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.
*
*
* @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.
*
* This is meant to return the CODE element in {@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 ......
} 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
* '}
* 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.
*
* 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 } or {@code } element to specify the
* language, as in {@code }. 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.
*
* Change log:
* cbeust, 2006/08/22
*
* Java annotations (start with "@") are now captured as literals ("lit")
*
* @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 } and {@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.
*
* 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.
*
*
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.} 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.
*
*
* The HTML DOM structure:
*
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
*
*
* corresponds to the HTML
* {@code
print 'Hello '
+ 'World';
}.
*
*
* It will produce the output:
*
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
*
*
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
*
*
*
* 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.
*
*
* @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.
*
* This is meant to return the CODE element in {@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 ......
} 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
* '
Gallery of themes for
code prettify
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.