code-prettify-2015-12-04/ 0000775 0000000 0000000 00000000000 12630354744 0014672 5 ustar 00root root 0000000 0000000 code-prettify-2015-12-04/.gitignore 0000664 0000000 0000000 00000000104 12630354744 0016655 0 ustar 00root root 0000000 0000000 *.tstamp
*~
distrib/google-code-prettify
distrib/prettify-small.tar
code-prettify-2015-12-04/CHANGES.md 0000664 0000000 0000000 00000013562 12630354744 0016273 0 ustar 00root root 0000000 0000000 # Known Issues
* Perl formatting is really crappy. Partly because the author is lazy and partly
because Perl is [hard](http://www.perlmonks.org/?node_id=663393) to parse.
* On some browsers, `
Below is the content of this page prettified. The
The line numbers to the left appear because the preceding comment
* The HTML DOM structure:
* corresponds to the HTML
* {@code print 'Hello '` 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 IE6, all newlines will be stripped from `
` elements because
of the way IE6 produces `innerHTML`. Workaround: use `
` for code with
newlines.
# Change Log
## 29 March 2007
* Added [tests](https://rawgit.com/google/code-prettify/master/tests/prettify_test.html#PHP)
for PHP support to address issue [#3](https://github.com/google/code-prettify/issues/3).
* Fixed bug [#6](https://github.com/google/code-prettify/issues/6): `prettyPrintOne`
was not halting. This was not reachable through the normal entry point.
* Fixed bug [#4](https://github.com/google/code-prettify/issues/4): recursing into a
script block or PHP tag that was not properly closed would not silently drop the content.
([test](https://rawgit.com/google/code-prettify/master/tests/prettify_test.html#issue4))
* Fixed bug [#8](https://github.com/google/code-prettify/issues/8): was eating tabs
([test](https://rawgit.com/google/code-prettify/master/tests/prettify_test.html#issue8))
* Fixed entity handling so that the caveat
> Caveats: please properly escape less-thans. `x<y` instead of `x
` blocks with embedded newlines.
## 3 October 2009
* Fixed prettifying of XML/HTML tags that contain uppercase letters.
## 19 July 2010
* Added support for line numbers. Bug [#22](https://github.com/google/code-prettify/issues/22)
* Added YAML support. Bug [#123](https://github.com/google/code-prettify/issues/123)
* Added VHDL support courtesy *Le Poussin*.
* IE performance improvements. Bug [#102](https://github.com/google/code-prettify/issues/102)
courtesy *jacobly*.
* A variety of markup formatting fixes courtesy *smain* and *thezbyg*.
* Fixed copy and paste in IE 6, 7, 8.
* Changed output to use ` ` instead of ` ` so that the output works
when embedded in XML. Bug [#108](https://github.com/google/code-prettify/issues/108).
## 7 September 2010
* Added support for coffeescript courtesy *Cezary Bartoszuk*.
## 4 March 2011
* Added a [themes gallery](https://rawgit.com/google/code-prettify/master/styles/index.html)
to showcase contributed styles.
* Added support for XQuery courtesy *Patrick Wied*, Nemerle courtesy *Zimin A.V.*,
and Latex support courtesy *Martin S*.
## 29 March 2011
* Fixed IE newline issues, and copying/pasting of prettified source code from IE.
This required significant internal changes but involves no API changes.
**Caveat**: `prettyPrintOne` injects the HTML passed to it into a `
` 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.
## 4 February 2013
* Language handlers for Dart, Erlang, Mumps, TCL, R, S., and others
* Bug fix: VB REM style comments.
* Bug fix: CSS color literals / ID selector confusion.
* Bug fix: IE8 line breaks.
## 24 February 2013
* Added a one script autoload&run mechanism and a way to embed hints in
processing instructions/comments. See
[example](https://rawgit.com/google/code-prettify/master/examples/quine.html).
## 4 March 2013
* Matlab language handler courtesy *Amro³*
## 28 Apr 2015
* Migrated to Github
code-prettify-2015-12-04/COPYING 0000664 0000000 0000000 00000025013 12630354744 0015726 0 ustar 00root root 0000000 0000000
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.
code-prettify-2015-12-04/Makefile 0000664 0000000 0000000 00000010246 12630354744 0016335 0 ustar 00root root 0000000 0000000 SHELL := /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 loader
clean:
rm -rf distrib.tstamp distrib loader.tstamp 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/google-code-prettify \
| perl -ne 'system("cp $$1 $$2") if m/^(\S+) (\S+)$$/ && ! -e $$2' \
&& touch lang-aliases.tstamp
loader : loader.tstamp lang-aliases.tstamp styles/*.css
loader.tstamp : distrib.tstamp
@cp distrib/google-code-prettify/*.{css,js} loader/ \
&& for f in styles/*.css; do \
$(YUI_COMPRESSOR) --type css $$f \
> loader/skins/$$(basename $$f); \
wc -c $$f loader/skins/$$(basename $$f) \
| grep -v total; \
done \
&& touch loader.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
code-prettify-2015-12-04/README.md 0000664 0000000 0000000 00000014771 12630354744 0016163 0 ustar 00root root 0000000 0000000 # Javascript code prettifier
An embeddable script that makes source-code snippets in HTML prettier.
[See an example](https://rawgit.com/google/code-prettify/master/examples/quine.html)
## Setup
* Include the script tag below in your document
```HTML
```
* See [Getting Started](docs/getting_started.md) to configure that URL with
options you need.
* Look at the [skin gallery](https://rawgit.com/google/code-prettify/master/styles/index.html)
and pick styles that suit you.
## Usage
Put code snippets in `
...
` or
`...
` and it will automatically be
pretty printed.
```HTML
class Voila {
public:
// Voila
static const string VOILA = "Voila";
// will not interfere with embedded tags.
}
```
## Discussion
Please use the official support group for discussions, suggestions, and
general feedback at:
http://groups.google.com/group/js-code-prettifier
## 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, doesn't work on
Smalltalk, OCaml, etc. without a language extension.
Other languages are supported via extensions:
[Apollo](src/lang-apollo.js);
[Basic](src/lang-basic.js);
[Clojure](src/lang-clj.js);
[CSS](src/lang-css.js);
[Dart](src/lang-dart.js);
[Erlang](src/lang-erlang.js);
[Go](src/lang-go.js);
[Haskell](src/lang-hs.js);
[Lasso](src/lang-lasso.js);
[Lisp, Scheme](src/lang-lisp.js);
[Llvm](src/lang-llvm.js);
[Logtalk](src/lang-logtalk.js);
[Lua](src/lang-lua.js);
[Matlab](src/lang-matlab.js);
[MLs: F#, Ocaml,SML](src/lang-ml.js);
[Mumps](src/lang-mumps.js);
[Nemerle](src/lang-n.js);
[Pascal](src/lang-pascal.js);
[Protocol buffers](src/lang-proto.js);
[R, S](src/lang-r.js);
[RD](src/lang-rd.js);
[Rust](src/lang-rust.js);
[Scala](src/lang-scala.js);
[SQL](src/lang-sql.js);
[Swift](src/lang-swift.js);
[TCL](src/lang-tcl.js);
[Latek](src/lang-tex.js);
[Visual Basic](src/lang-vb.js);
[VHDL](src/lang-vhdl.js);
[Wiki](src/lang-wiki.js);
[XQ](src/lang-xq.js);
[YAML](src/lang-yaml.js)
If you'd like to add an extension for your favorite language, please
look at `src/lang-lisp.js` and submit a pull request.
### How do I specify the language of my code?
You don't need to specify the language since `PR.prettyprint()`
will guess. You can specify a language by specifying the language extension
along with the `prettyprint` class:
```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".
```
You may also use the
[HTML 5](http://dev.w3.org/html5/spec-author-view/the-code-element.html#the-code-element)
convention of embedding a `code` element inside the `PRE` and using
`language-java` style classes.
E.g. `
`
### It doesn't work on `...
// 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.
```HTML
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](https://rawgit.com/google/code-prettify/master/tests/prettify_test.html#issue22).
### 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
```JavaScript
addEventListener('load', PR.prettyPrint, false);
```
wrap it in a closure like
```JavaScript
addEventListener('load', function (event) { PR.prettyPrint() }, false);
```
so that the browser does not pass an event object to `PR.prettyPrint`
which will confuse it.
### How can I customize the colors and styles of my code?
Prettify adds `` with `class`es describing the kind of code.
You can create CSS styles to matches these classes.
See the [theme gallery](https://rawgit.com/google/code-prettify/master/styles/index.html)
for examples.
### I can't add classes to my code (because it comes from Markdown, etc.)
Instead of `` you can use a comment
or processing instructions that survives processing instructions :
`` works as explained in
[Getting Started](docs/getting_started.md).
### How can I put line numbers on every line instead of just every fifth line?
Prettify puts lines into an HTML list element so that line numbers
aren't caught by copy/paste, and the line numbering is controlled by
CSS in the default stylesheet, `prettify.css`.
```HTML
```
should turn line numbering back on for the other lines.
## License
[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)
code-prettify-2015-12-04/docs/ 0000775 0000000 0000000 00000000000 12630354744 0015622 5 ustar 00root root 0000000 0000000 code-prettify-2015-12-04/docs/getting_started.md 0000664 0000000 0000000 00000010577 12630354744 0021345 0 ustar 00root root 0000000 0000000 # Getting Started
## How to style code in your web-pages
## Getting Started
You can load the Prettify script to highlight code in your web pages.
It adds styles to code snippets so that token boundaries stand out and
your readers can get the gist of your code without having to mentally
perform a left-to-right parse.
## Marking code sections
The prettyprinter looks for `
`, `
`, or `
source code here
```
and adds ``s to colorize keywords, strings, comments, and other
token types.
If you're using Markdown or some other HTML generator that does not
add classes, you can alternatively ask the prettifier to target your
code by preceding it with a processing instruction thus:
```HTML
code here
```
[Larger example](https://rawgit.com/google/code-prettify/master/examples/quine.html)
## Auto-Loader
You can load the JavaScript and CSS for prettify via one URL
```HTML
```
will load the entire system and schedule the prettifier to run on page
load. There are a variety of additional options you can specify (as
CGI arguments) to configure the runner.
| CGI parameter | default | meaning |
| ------------- | ------- | ------- |
| autoload=(true, false) | true | run automatically on page load |
| lang=... | none | Loads the language handler for the given language which is usually the file extension for source files for that language. See the [index of language handlers](https://github.com/google/code-prettify/tree/master/src). If specified multiple times (`?lang=css&lang=ml`) then all are loaded. |
| skin=... | none | See the [skin gallery](https://cdn.rawgit.com/google/code-prettify/master/styles/index.html). If specified multiple times, the first one to successfully load is used. |
| callback=js_ident | | `window.exports["js_ident"]` will be called when prettyprinting finishes. If specified multiple times, all are called. |
For example
```HTML
```
specifies the `lang` parameter to also load the CSS language extension
and the `skin` parameter to load the
[*sunburst*](https://cdn.rawgit.com/google/code-prettify/master/styles/index.html#sunburst) skin.
## Serving your own JS & CSS
You can
[download](https://raw.githubusercontent.com/google/code-prettify/master/distrib/prettify-small.tgz)
the scripts and styles and serve them yourself. Make sure to include
both the script and a stylesheet:
```HTML
```
and then run the `prettyPrint` function once your page has finished
loading. One way to do this is via the `onload` handler thus:
```HTML
```
## Styling
The prettifier only adds `class`es; it does not specify exact colors
or fonts, so you can swap in a different stylesheet to change the way
code is prettified.
The easiest way to create your own stylesheet is by starting with one
from the
[style gallery](https://cdn.rawgit.com/google/code-prettify/master/styles/index.html)
and tweaking it.
You can use CSS `@media` rules to specify styles that work well with
printers (for example, dark text on a white background) when someone
tries to print it.
## Language Hints
Prettify makes a best effort to guess the language but works best with
C-like and HTML-like languages. For others, there are special
language handlers that are chosen based on language hints.
```HTML
(friends 'of '(parentheses))
```
uses the `lang-scm` hint to specify that the code is Scheme code.
```HTML
(friends 'of '(parentheses))
```
also works.
## Line Numbering
The `linenums` class in
```HTML
Many
lines
of
code
```
tells the prettyprinter to insert an `` element and `
lots of code
```
also works.
code-prettify-2015-12-04/examples/ 0000775 0000000 0000000 00000000000 12630354744 0016510 5 ustar 00root root 0000000 0000000 code-prettify-2015-12-04/examples/quine.html 0000664 0000000 0000000 00000003545 12630354744 0020526 0 ustar 00root root 0000000 0000000
Making Quines Prettier
<pre>
element is prettified because it has class="prettyprint"
and
because the sourced script loads a JavaScript library that styles source
code.
<?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.
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
*
*
+ '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 }; } code-prettify-2015-12-04/js-modules/extractSourceSpans_test.html 0000664 0000000 0000000 00000011404 12630354744 0024541 0 ustar 00root root 0000000 0000000Test space preserved in PRE | ||
---|---|---|
print 'Hello ' |
^print ^'Hello '^\n^ + '<World>';^ |
|
Test class="nocode" | ||
1. print 'Hello ' |
^print ^'Hello '^\n^ + '<World>';^ |
|
Test whitespace normalized in code | ||
print 'Hello '
+ '<World>'; |
^print ^'Hello ' + '<World>';^ |
|
Test XMP | ||
^print 'Hello '\n + '<World>';^ |
||
Test tabs | ||
print 'Hello ' + '<World>'; |
^print 'Hello '\n\t+ '<World>';^ |
|
Test number lines output | ||
|
^print ^'Hello '^\n^ + '<World>';^^ |
Test Nothing to Split | ||
---|---|---|
Hello, World! |
|
|
Test Normalized Spaces | ||
Hello,
World! |
|
|
Test BR | ||
Hello, |
|
|
Test line breaks | ||
Hello, there World! |
|
|
Test line breaks with followers | ||
Hello, there World! |
|
|
Test nocode | ||
Hello,
there
World! |
|
|
Test link | ||
Hello, there World! |
||
Test blank lines | ||
One Three |
|
* 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:
} 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.
*
} 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,finally,final,implements,import," +
"instanceof,interface,null,native,package,strictfp,super,synchronized," +
"throws,transient"];
var CSHARP_KEYWORDS = [COMMON_KEYWORDS,
"abstract,as,base,bool,by,byte,checked,decimal,delegate,descending," +
"dynamic,event,finally,fixed,foreach,from,group,implicit,in,interface," +
"internal,into,is,let,lock,null,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,instanceof,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 SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_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.
*
* 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
* '
Recombine Tags And Decorations
Test Single Decoration
"Hello, World!"
[0, 'str']
"Hello, World!"
Test Single Span
print "Hello, <World>!";
[0, 'kwd', 5, 'pln', 6, 'str', 14, 'tag', 21, 'str', 23, 'pun']
print "Hello, <World>!";
Test Interleaved
print "Hello, <World>!";
[0, 'kwd', 5, 'pln', 6, 'str', 14, 'tag', 21, 'str', 23, 'pun']
print "Hello, <World>!";
Last modified: Tue Mar 29 10:41:34 PDT 2011