diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..433f78b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# temporary files +*~ +*.swp +.DS_Store + +# package managers +/node_modules/ +/bower_components/ +npm-debug.log +.bower.json + +# generated files +#/src/prettify.js +#/src/run_prettify.js +#/loader/*.js +#/loader/*.css +#/loader/skins/*.css +#/distrib/*.zip diff --git a/CHANGES.html b/CHANGES.html deleted file mode 100644 index 32665d77..00000000 --- a/CHANGES.html +++ /dev/null @@ -1,162 +0,0 @@ - -
- -<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.
- ` 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://raw.githack.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://raw.githack.com/google/code-prettify/master/tests/prettify_test.html#js_script))
+ * Fixed bug [#8](https://github.com/google/code-prettify/issues/8): was eating tabs
+ ([test](https://raw.githack.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 and use `"` instead of `"` for string delimiters.
+
+ is no longer applicable.
+ * Added *noisefree*'s C# patch [#7](https://github.com/google/code-prettify/issues/7)
+ * Added a [distribution](http://google-code-prettify.googlecode.com/files/prettify-small.zip)
+ that has comments and whitespace removed to reduce download size from 45.5kB
+ to 12.8kB.
+
+## 4 Jul 2008
+
+ * Added [#17](https://github.com/google/code-prettify/issues/17) language specific
+ formatters that are triggered by the presence of a `lang-`
+ * Fixed bug [#29](https://github.com/google/code-prettify/issues/29): python
+ handling of `'''string'''`
+ * Fixed bug: `/` in regex `[charsets] should not end regex`
+
+## 5 Jul 2008
+
+ * Defined language extensions for Lisp and Lua
+
+## 14 Jul 2008
+
+ * Language handlers for F#, OCAML, SQL
+ * Support for `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](https://github.com/google/code-prettify/issues/22)
+ [testcase](https://raw.githack.com/google/code-prettify/master/tests/prettify_test.html#issue22).
+
+## 6 Jan 2009
+
+ * Language handlers for Visual Basic, Haskell, CSS, and WikiText
+ * Added `.mxml` extension to the markup style handler for
+ Flex [MXML files](http://en.wikipedia.org/wiki/MXML).
+ See issue [#37](https://github.com/google/code-prettify/issues/37).
+ * Added `.m` extension to the C style handler so that Objective C source files
+ properly highlight. See issue [#58](https://github.com/google/code-prettify/issues/58).
+ * Changed HTML lexer to use the same embedded source mechanism as the wiki
+ language handler, and changed to use the registered CSS handler for STYLE
+ element content.
+
+## 21 May 2009
+
+ * Rewrote to improve performance on large files.
+ See [benchmarks](http://mikesamuel.blogspot.com/2009/05/efficient-parsing-in-javascript.html).
+ * Fixed bugs with highlighting of Haskell line comments, Lisp number literals,
+ Lua strings, C preprocessor directives, newlines in Wiki code on Windows, and
+ newlines in IE6.
+
+## 14 August 2009
+
+ * Fixed prettifying of `` 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://raw.githack.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://raw.githack.com/google/code-prettify/master/examples/quine.html).
+
+## 4 March 2013
+
+ * Matlab language handler courtesy *Amro³*
+
+## 28 Apr 2015
+
+ * Migrated to Github
diff --git a/Gruntfile.js b/Gruntfile.js
new file mode 100644
index 00000000..918a6b05
--- /dev/null
+++ b/Gruntfile.js
@@ -0,0 +1,263 @@
+/**
+ * google-code-prettify
+ * https://github.com/google/code-prettify
+ *
+ * Copyright (C) 2017 Google Inc.
+ * Licensed under Apache 2.0 license.
+ */
+
+module.exports = function (grunt) {
+ 'use strict';
+
+ // project configuration
+ grunt.initConfig({
+ // metadata
+ pkg: grunt.file.readJSON('package.json'),
+
+ // grunt-preprocess
+ preprocess: {
+ // https://github.com/jsoverson/preprocess#optionstype
+ options: {
+ // renders @include directives (similar to SSI server-side includes)
+ // where JS files are resolved relative to this directory
+ srcDir: 'js-modules',
+ type: 'js'
+ },
+ prettify: {
+ src: 'js-modules/prettify.js',
+ dest: 'src/prettify.js'
+ },
+ runprettify: {
+ options: {
+ context: {
+ // to control where defs.js is included (top level)
+ RUN_PRETTIFY: true
+ }
+ },
+ src: 'js-modules/run_prettify.js',
+ dest: 'src/run_prettify.js'
+ },
+ nodeprettify: {
+ options: {
+ context: {
+ RUN_PRETTIFY: true
+ }
+ },
+ src: 'js-modules/node_prettify.js',
+ dest: 'src/node_prettify.js'
+ }
+ },
+
+ // grunt-contrib-copy
+ copy: {
+ prettify: {
+ options: {
+ process: function (content) {
+ // trim trailing whitespaces in blank lines added by preprocess
+ return content.replace(/[ \f\t\v]+$/gm, '');
+ }
+ },
+ files: [
+ {src: 'src/prettify.js', dest: 'src/prettify.js'},
+ {src: 'src/run_prettify.js', dest: 'src/run_prettify.js'},
+ {src: 'src/node_prettify.js', dest: 'src/node_prettify.js'}
+ ]
+ },
+ langs: {
+ options: {
+ process: function (content) {
+ // replace PR.PR_* token names with inlined strings
+ return content
+ .replace(/\bPR\.PR_ATTRIB_NAME\b/g, '"atn"')
+ .replace(/\bPR\.PR_ATTRIB_VALUE\b/g, '"atv"')
+ .replace(/\bPR\.PR_COMMENT\b/g, '"com"')
+ .replace(/\bPR\.PR_DECLARATION\b/g, '"dec"')
+ .replace(/\bPR\.PR_KEYWORD\b/g, '"kwd"')
+ .replace(/\bPR\.PR_LITERAL\b/g, '"lit"')
+ .replace(/\bPR\.PR_NOCODE\b/g, '"nocode"')
+ .replace(/\bPR\.PR_PLAIN\b/g, '"pln"')
+ .replace(/\bPR\.PR_PUNCTUATION\b/g, '"pun"')
+ .replace(/\bPR\.PR_SOURCE\b/g, '"src"')
+ .replace(/\bPR\.PR_STRING\b/g, '"str"')
+ .replace(/\bPR\.PR_TAG\b/g, '"tag"')
+ .replace(/\bPR\.PR_TYPE\b/g, '"typ"');
+ }
+ },
+ files: [{
+ expand: true,
+ cwd: 'loader/',
+ src: ['lang-*.js'],
+ dest: 'loader/'
+ }]
+ }
+ },
+
+ // ./tasks/aliases.js
+ aliases: {
+ langs: {
+ src: 'loader/lang-*.js',
+ filter: function (src) {
+ // skip files that are themselves aliases created in previous runs
+ return grunt.file.exists(src.replace(/^loader/, 'src'));
+ }
+ }
+ },
+
+ // grunt-contrib-uglify
+ uglify: {
+ // https://github.com/mishoo/UglifyJS2#usage
+ options: {
+ report: 'gzip',
+ ASCIIOnly: true,
+ maxLineLen: 500,
+ screwIE8: false
+ },
+ prettify: {
+ options: {
+ compress: {
+ global_defs: {'IN_GLOBAL_SCOPE': true}
+ },
+ wrap: true
+ },
+ src: 'src/prettify.js',
+ dest: 'loader/prettify.js'
+ },
+ runprettify: {
+ options: {
+ compress: {
+ global_defs: {'IN_GLOBAL_SCOPE': false}
+ },
+ wrap: true
+ },
+ src: 'src/run_prettify.js',
+ dest: 'loader/run_prettify.js'
+ },
+ langs: {
+ files: [{
+ expand: true,
+ cwd: 'src/',
+ src: ['lang-*.js'],
+ dest: 'loader/',
+ ext: '.js'
+ }]
+ }
+ },
+
+ // google-closure-compiler
+ 'closure-compiler': {
+ // https://github.com/google/closure-compiler/wiki
+ options: {
+ // 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.
+ warning_level: 'VERBOSE',
+ language_in: 'ECMASCRIPT5',
+ compilation_level: 'ADVANCED',
+ charset: 'US-ASCII'
+ },
+ prettify: {
+ options: {
+ externs: 'tools/closure-compiler/amd-externs.js',
+ define: 'IN_GLOBAL_SCOPE=true',
+ output_wrapper: '!function(){%output%}()'
+ },
+ src: '<%= uglify.prettify.src %>',
+ dest: '<%= uglify.prettify.dest %>'
+ },
+ runprettify: {
+ options: {
+ externs: 'tools/closure-compiler/amd-externs.js',
+ define: 'IN_GLOBAL_SCOPE=false',
+ output_wrapper: '!function(){%output%}()'
+ },
+ src: '<%= uglify.runprettify.src %>',
+ dest: '<%= uglify.runprettify.dest %>'
+ },
+ langs: {
+ options: {
+ externs: 'js-modules/externs.js'
+ },
+ files: '<%= uglify.langs.files %>'
+ }
+ },
+
+ // ./tasks/gcc.js
+ gcc: {
+ // same as 'closure-compiler:langs'
+ langs: {
+ options: {
+ externs: 'js-modules/externs.js'
+ },
+ files: '<%= uglify.langs.files %>'
+ }
+ },
+
+ // grunt-contrib-cssmin
+ cssmin: {
+ // https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-api
+ options: {
+ report: 'gzip'
+ },
+ prettify: {
+ src: 'src/prettify.css',
+ dest: 'loader/prettify.css'
+ },
+ skins: {
+ files: [{
+ expand: true,
+ cwd: 'styles/',
+ src: ['*.css'],
+ dest: 'loader/skins/',
+ ext: '.css'
+ }]
+ }
+ },
+
+ // grunt-contrib-compress
+ compress: {
+ zip: {
+ options: {
+ archive: 'distrib/prettify-small.zip',
+ mode: 'zip',
+ level: 9
+ },
+ files: [{
+ expand: true,
+ cwd: 'loader/',
+ src: ['*.js', '*.css', 'skins/*.css'],
+ dest: 'google-code-prettify/'
+ }]
+ }
+ },
+
+ // grunt-contrib-clean
+ clean: {
+ js: ['src/prettify.js', 'src/run_prettify.js', 'loader/*.js'],
+ css: ['loader/*.css', 'loader/skins/*.css'],
+ zip: ['distrib/*.zip']
+ }
+ });
+
+ // load plugins that provide tasks
+ require('google-closure-compiler').grunt(grunt);
+ grunt.loadTasks('./tasks');
+ grunt.loadNpmTasks('grunt-preprocess');
+ grunt.loadNpmTasks('grunt-contrib-copy');
+ grunt.loadNpmTasks('grunt-contrib-uglify');
+ grunt.loadNpmTasks('grunt-contrib-cssmin');
+ grunt.loadNpmTasks('grunt-contrib-compress');
+ grunt.loadNpmTasks('grunt-contrib-clean');
+
+ // register task aliases
+ grunt.registerTask('default', [
+ //'clean',
+ 'preprocess',
+ 'copy:prettify',
+ 'gcc',
+ 'copy:langs',
+ 'aliases',
+ 'cssmin',
+ 'compress'
+ ]);
+};
diff --git a/Makefile b/Makefile
deleted file mode 100644
index a1c7f62e..00000000
--- a/Makefile
+++ /dev/null
@@ -1,97 +0,0 @@
-SHELL := /bin/bash
-
-CLOSURE_COMPILER=java -jar closure-compiler/compiler.jar \
- --warning_level VERBOSE \
- --language_in ECMASCRIPT5 \
- --compilation_level ADVANCED_OPTIMIZATIONS
-# 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 yui-compressor/yuicompressor-2.4.4.jar \
- --charset UTF-8
-
-TAR_ROOT=distrib/google-code-prettify
-
-all: distrib
-
-clean:
- rm -rf distrib.tstamp distrib src/prettify.js src/run_prettify.js
-
-src/prettify.js: js-modules/*.js js-modules/*.pl
- @if [ -e "$@" ]; then chmod +w "$@"; fi
- @perl js-modules/js_include.pl "$$(basename $@)" > "$@"
- @if [ -e "$@" ]; then chmod -w "$@"; fi
-
-src/run_prettify.js: js-modules/*.js js-modules/*.pl
- @if [ -e "$@" ]; then chmod +w "$@"; fi
- @perl js-modules/js_include.pl "$$(basename $@)" > "$@"
- @if [ -e "$@" ]; then chmod -w "$@"; fi
-
-distrib: distrib.tstamp distrib/prettify-small.tgz distrib/prettify-small.zip distrib/prettify-small.tar.bz2
- @wc -c distrib/prettify-small.{tar.bz2,tgz,zip} \
- | grep -v total
-
-distrib.tstamp: src/prettify.js src/run_prettify.js src/*.js src/*.css
- @echo Compiling
- @mkdir -p $(TAR_ROOT)
- @for f in src/*.css; do \
- $(YUI_COMPRESSOR) --type css $$f \
- > $(TAR_ROOT)/$$(basename $$f); \
- wc -c $$f $(TAR_ROOT)/$$(basename $$f) \
- | grep -v total; \
- done
- @$(CLOSURE_COMPILER) --js src/prettify.js \
- --externs closure-compiler/console-externs.js \
- --externs 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 closure-compiler/console-externs.js \
- --externs 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
-
-%.tgz: %.tar
- @gzip -c -9 $^ > $@
-
-%.tar.bz2: %.tar
- @bzip2 -9f $^
-
-distrib/prettify-small.tar: distrib.tstamp
- @pushd distrib >& /dev/null; \
- tar cf ../$@ google-code-prettify; \
- popd >& /dev/null
-
-distrib/prettify-small.zip: distrib.tstamp
- @pushd distrib >& /dev/null; \
- rm -f ../$@; \
- zip -q -9 -r ../$@ google-code-prettify; \
- popd >& /dev/null
diff --git a/README-zh-Hans.html b/README-zh-Hans.html
deleted file mode 100644
index 69bf7aed..00000000
--- a/README-zh-Hans.html
+++ /dev/null
@@ -1,143 +0,0 @@
-
-
-
-
-
- Javascript code prettifier
-
-
-
-
-
-
-
-
-
- Javascript code prettifier
- Javascript 代码美容师
- 安装使用
-
- - 下载 文件
-
- 在你的文件中包含这儿的脚本和样式表(你要保证这儿的 css 和 js 文件按在你的服务器上, 并且调整在 script 和 link标签中的路径)
-
-<link href="prettify.css" type="text/css" rel="stylesheet" />
-<script type="text/javascript" src="prettify.js"></script>
- - 添加
onload="prettyPrint()"
到你的文件的 body 标签中.
- - 修改样式表,使用你自己喜欢的颜色.
-
-
- 使用方法
- 在
- <pre class="prettyprint">...</pre> 或 <code class="prettyprint">...</code>
- 中间放上代码片段,它就会自动被美化了.
-
-
-
- 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.
-}
-
-
-
- 常见问题
- 它是为什么语言工作的?
- prettify.js中的注释是权威的,但是它的语法分析程序可以在很多语言中使用,包括 C ,
- Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, 和 Makefiles.
- 它在 Ruby, PHP, VB, 和 Awk 中还算可以,而且也可以在 Perl 和 Ruby的合适子集中起作用,但是, 因为注释的约定,它对
- Smalltalk, 或 CAML类似的语言起作用.
-
-
- LISP系列的语言可以使用一个拓展lang-lisp.js
.
对于 CSS
,
- Haskell
,
- Lua
,
- OCAML, SML, F#
,
- Visual Basic
,
- SQL
,
- Protocol Buffers
, 和
- WikiText
..也是类似的
如果你想给你喜欢的语言写个拓展版本, 请参阅src/lang-lisp.js ,并写一个包括你的语言的拓展的 发布 和一个测试用例.
-
- 如何指定我的代码在哪种语言里?
- 你不需要指定语言环境,因为 prettyprint()
- 会对此进行猜测. 你可以使用 prettyprint
这个类通过指定语言的拓展名来指定语言,就像这样:
- <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>
-
- 它在混淆代码例子上不起作用吗?
- 是的. 美化混淆代码就像给小猪涂口红,也就是不在这个工具的范围内.
-
- 它可以在那些浏览器上工作?
- 这个工具已经在 IE 6, Firefox 1.5 & 2, 和 Safari 2.0.4 上测试通过. 打开 测试页面 ,看看它能不能在你的浏览器上起作用.
-
- 有什么改变?
- 查看 变化日志
-
- 为什么Prettyprinting 对WordPress中的字符串没用?
- 很显然,wordpress 在 "smart quoting" 时会改变关闭符号.
- 这使得关闭符号跟开始符号不配套.
-
这和复制粘贴代码一样,破坏了美化作用. 去
- WordPress's help center 查看更多关于如何关闭插入代码段时的"smart quoting"的信息.
-
- 如何在我的代码中加入行号? (Out of date -- see English version)
- 你可以使用 nocode
类来标记 span 标记不是代码.
-
<pre class=prettyprint>
-<span class="nocode">1:</span> /* This is line 1 of my code
-<span class="nocode">2:</span> * and here's line 2 */
-<span class="nocode">3:</span> print("I'm line number 3");
-</pre>
得到
-
-1: /* This is line 1 of my code
-2: * and here's line 2 */
-3: print("I'm line number 3");
-
-
- 查看一个更完整的例子: issue22
- testcase.
-
- 我得到了这样一条错误信息 "a is not a function" 或 "opt_whenDone is not a function"
- 如果你通过事件句柄条用 prettyPrint
, 把它隐藏到一个函数中.
不要这么写
-
- addEventListener('load', prettyPrint, false);
-
而要这么写
-
- addEventListener('load', function (event) { prettyPrint() }, false);
-
这样的话,浏览器就不会把时间对象传递给 prettyPrint
,事件对象会让它困惑的.
-
-
-
-
-
-
diff --git a/README.html b/README.html
deleted file mode 100644
index 3049a43a..00000000
--- a/README.html
+++ /dev/null
@@ -1,235 +0,0 @@
-
-
-
-
- Javascript code prettifier
-
-
-
-
-
-
-
-
-
- Languages : CH
- Javascript code prettifier
-
- Setup
-
- - Download a distribution
-
- Include the script and stylesheets in your document
- (you will need to make sure the css and js file are on your server, and
- adjust the paths in the script and link tag)
-
-<link href="prettify.css" type="text/css" rel="stylesheet" />
-<script type="text/javascript" src="prettify.js"></script>
- - Add
onload="prettyPrint()"
to your
- document's body tag.
- - Modify the stylesheet to get the coloring you prefer
-
-
- Usage
- Put code snippets in
- <pre class="prettyprint">...</pre>
- or <code class="prettyprint">...</code>
- and it will automatically be pretty printed.
-
-
-
- The original
- Prettier
-
- class Voila {
-public:
- // Voila
- static const string VOILA = "Voila";
-
- // will not interfere with embedded tags.
-}
-
- class Voila {
-public:
- // Voila
- static const string VOILA = "Voila";
-
- // will not interfere with embedded tags.
-}
-
-
- FAQ
- For which languages does it work?
- The comments in prettify.js are authoritative but the lexer
- should work on a number of languages including C and friends,
- Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles.
- 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, or CAML-like languages.
-
- LISPy languages are supported via an extension:
- lang-lisp.js
.
- And similarly for
- Clojure
,
- CSS
,
- Erlang
,
- Go
,
- Haskell
,
- Lua
,
- OCAML, SML, F#
,
- Nemerle
,
- Protocol Buffers
,
- Scala
,
- SQL
,
- TeX, LaTeX
,
- VHDL
,
- Visual Basic
,
- WikiText
,
- XQuery
, and
- YAML
.
-
-
If you'd like to add an extension for your favorite language, please
- look at src/lang-lisp.js and file an
- issue including your language extension, and a testcase.
-
- How do I specify the language of my code?
- You don't need to specify the language since prettyprint()
- will guess. You can specify a language by specifying the language extension
- along with the prettyprint
class like so:
- <pre class="prettyprint lang-html">
- The lang-* class specifies the language file extensions.
- File extensions supported by default include
- "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html",
- "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh",
- "xhtml", "xml", "xsl".
-</pre>
-
- You may also use the
- HTML 5 convention of embedding a code element inside the
- PRE
and using language-java
style classes.
- E.g.
...
-
- It doesn't work on <obfuscated code sample>?
- Yes. Prettifying obfuscated code is like putting lipstick on a pig
- — i.e. outside the scope of this tool.
-
- Which browsers does it work with?
- It's been tested with IE 6, Firefox 1.5 & 2, and Safari 2.0.4.
- Look at the test page to see if it
- works in your browser.
-
- What's changed?
- See the change log
-
- Why doesn't Prettyprinting of strings work on WordPress?
- Apparently wordpress does "smart quoting" which changes close quotes.
- This causes end quotes to not match up with open quotes.
-
This breaks prettifying as well as copying and pasting of code samples.
- See
- WordPress's help center for info on how to stop smart quoting of code
- snippets.
-
- How do I put line numbers in my code?
- You can use the linenums
class to turn on line
- numbering. If your code doesn't start at line number 1, you can
- add a colon and a line number to the end of that class as in
- linenums:52
.
-
-
For example
-
<pre class="prettyprint linenums:4"
->// This is line 4.
-foo();
-bar();
-baz();
-boo();
-far();
-faz();
-<pre>
- produces
-// This is line 4.
-foo();
-bar();
-baz();
-boo();
-far();
-faz();
-
-
- How do I prevent a portion of markup from being marked as code?
- You can use the nocode
class to identify a span of markup
- that is not code.
-
<pre class=prettyprint>
-int x = foo(); /* This is a comment <span class="nocode">This is not code</span>
- Continuation of comment */
-int y = bar();
-</pre>
-produces
-
-int x = foo(); /* This is a comment This is not code
- Continuation of comment */
-int y = bar();
-
-
- For a more complete example see the issue22
- testcase.
-
- I get an error message "a is not a function" or "opt_whenDone is not a function"
- If you are calling prettyPrint
via an event handler, wrap it in a function.
- Instead of doing
-
- addEventListener('load', prettyPrint, false);
-
- wrap it in a closure like
-
- addEventListener('load', function (event) { prettyPrint() }, false);
-
- so that the browser does not pass an event object to prettyPrint
which
- will confuse it.
-
- How can I customize the colors and styles of my code?
-
- Prettify adds <span>
with class
es describing
- the kind of code. You can create CSS styles to matches these
- classes.
- See the
-
- theme gallery for examples.
-
-
-
-
-
-
-
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..41cd727e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,248 @@
+# Status: Archived
+
+
+
+This repository has been archived and is no longer maintained.
+
+---
+
+# JavaScript code prettifier
+
+Announcement: [**Action required** *rawgit.com* is going away](https://groups.google.com/forum/#!topic/js-code-prettifier/IFHev_kLm30).
+
+An embeddable script that makes source-code snippets in HTML prettier.
+
+* Works on HTML pages.
+* Works even if code contains embedded links, line numbers, etc.
+* Simple API: include some JS & CSS and add an onload handler.
+* Lightweights: small download and does not block page from loading while
+ running.
+* Customizable styles via CSS. See the [themes gallery][1].
+* Supports all C-like, Bash-like, and XML-like languages. No need to specify
+ the language.
+* Extensible language handlers for other languages. You can specify the
+ language.
+* Widely used with good cross-browser support. Powers https://code.google.com/
+ and http://stackoverflow.com/
+
+[See an example][2].
+
+## 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][1] 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.
+}
+```
+
+## 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, Makefile, 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);
+[LaTeX](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][3] convention of embedding a `` element
+inside the `` and using `language-java` style classes:
+
+```HTML
+...
+```
+
+### It doesn't work on "obfuscated code sample"?
+
+Yes. Prettifying obfuscated code is like putting lipstick on a pig —
+i.e. outside the scope of this tool.
+
+### Which browsers does it work with?
+
+It's been tested with IE 6, Firefox 1.5 & 2, and Safari 2.0.4. Look at
+[the tests][4] to see if it works in your browser.
+
+### What's changed?
+
+See the [changelog](CHANGES.md).
+
+### Why doesn't Prettyprinting of strings work on WordPress?
+
+Apparently wordpress does "smart quoting" which changes close quotes. This
+causes end quotes to not match up with open quotes.
+
+This breaks prettifying as well as copying and pasting of code samples. See
+[WordPress's help center][5] for info on how to stop smart quoting of code
+snippets.
+
+### How do I put line numbers in my code?
+
+You can use the `linenums` class to turn on line numbering. If your code
+doesn't start at line number `1`, you can add a colon and a line number to the
+end of that class as in `linenums:52`. For example:
+
+```HTML
+// 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 [issue #22 testcase][6].
+
+### 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][1] 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`.
+
+The following should turn line numbering back on for the other lines:
+
+```HTML
+
+```
+
+## Discussion
+
+Please use the official [support group][7] for discussions, suggestions, and
+general feedback.
+
+## License
+
+[Apache License 2.0](COPYING)
+
+
+[1]: https://raw.githack.com/google/code-prettify/master/styles/index.html
+[2]: https://raw.githack.com/google/code-prettify/master/examples/quine.html
+[3]: http://dev.w3.org/html5/spec-author-view/the-code-element.html#the-code-element
+[4]: https://raw.githack.com/google/code-prettify/master/tests/prettify_test.html
+[5]: http://wordpress.org/support/topic/125038
+[6]: https://raw.githack.com/google/code-prettify/master/tests/prettify_test.html#issue22
+[7]: http://groups.google.com/group/js-code-prettifier
diff --git a/bower.json b/bower.json
new file mode 100644
index 00000000..27b13817
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,40 @@
+{
+ "name": "code-prettify",
+ "description": "Google Code Prettify",
+ "authors": [
+ "Google"
+ ],
+ "license": "Apache-2.0",
+ "homepage": "https://github.com/google/code-prettify",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/google/code-prettify.git"
+ },
+ "keywords": [
+ "syntax",
+ "highlight",
+ "highlighting",
+ "source",
+ "code",
+ "prettify",
+ "google"
+ ],
+ "main": [
+ "src/prettify.js",
+ "src/prettify.css"
+ ],
+ "moduleType": [
+ "globals",
+ "amd"
+ ],
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "distrib",
+ "js-modules",
+ "tasks",
+ "tests",
+ "tools"
+ ]
+}
diff --git a/closure-compiler/COPYING b/closure-compiler/COPYING
deleted file mode 100644
index d6456956..00000000
--- a/closure-compiler/COPYING
+++ /dev/null
@@ -1,202 +0,0 @@
-
- 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
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- 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.
diff --git a/closure-compiler/README b/closure-compiler/README
deleted file mode 100644
index dfffa7f9..00000000
--- a/closure-compiler/README
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright 2009 The Closure Compiler Authors.
- *
- * 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.
- */
-
-//
-// Contents
-//
-
-The Closure Compiler performs checking, instrumentation, and
-optimizations on JavaScript code. The purpose of this README is to
-explain how to build and run the Closure Compiler.
-
-The Closure Compiler requires Java 6 or higher.
-http://www.java.com/
-
-
-//
-// Building The Closure Compiler
-//
-
-There are three ways to get a Closure Compiler executable.
-
-1) Use one we built for you.
-
-Pre-built Closure binaries can be found at
-http://code.google.com/p/closure-compiler/downloads/list
-
-
-2) Check out the source and build it with Apache Ant.
-
-First, check out the full source tree of the Closure Compiler. There
-are instructions on how to do this at the project site.
-http://code.google.com/p/closure-compiler/source/checkout
-
-Apache Ant is a cross-platform build tool.
-http://ant.apache.org/
-
-At the root of the source tree, there is an Ant file named
-build.xml. To use it, navigate to the same directory and type the
-command
-
-ant jar
-
-This will produce a jar file called "build/compiler.jar".
-
-
-3) Check out the source and build it with Eclipse.
-
-Eclipse is a cross-platform IDE.
-http://www.eclipse.org/
-
-Under Eclipse's File menu, click "New > Project ..." and create a
-"Java Project." You will see an options screen. Give the project a
-name, select "Create project from existing source," and choose the
-root of the checked-out source tree as the existing directory. Verify
-that you are using JRE version 6 or higher.
-
-Eclipse can use the build.xml file to discover rules. When you
-navigate to the build.xml file, you will see all the build rules in
-the "Outline" pane. Run the "jar" rule to build the compiler in
-build/compiler.jar.
-
-
-//
-// Running The Closure Compiler
-//
-
-Once you have the jar binary, running the Closure Compiler is straightforward.
-
-On the command line, type
-
-java -jar compiler.jar
-
-This starts the compiler in interactive mode. Type
-
-var x = 17 + 25;
-
-then hit "Enter", then hit "Ctrl-Z" (on Windows) or "Ctrl-D" (on Mac or Linux)
-and "Enter" again. The Compiler will respond:
-
-var x=42;
-
-The Closure Compiler has many options for reading input from a file,
-writing output to a file, checking your code, and running
-optimizations. To learn more, type
-
-java -jar compiler.jar --help
-
-You can read more detailed documentation about the many flags at
-http://code.google.com/closure/compiler/docs/gettingstarted_app.html
-
-
-//
-// Compiling Multiple Scripts
-//
-
-If you have multiple scripts, you should compile them all together with
-one compile command.
-
-java -jar compiler.jar --js=in1.js --js=in2.js ... --js_output_file=out.js
-
-The Closure Compiler will concatenate the files in the order they're
-passed at the command line.
-
-If you need to compile many, many scripts together, you may start to
-run into problems with managing dependencies between scripts. You
-should check out the Closure Library. It contains functions for
-enforcing dependencies between scripts, and a tool called calcdeps.py
-that knows how to give scripts to the Closure Compiler in the right
-order.
-
-http://code.google.com/p/closure-library/
-
-//
-// Licensing
-//
-
-Unless otherwise stated, all source files are licensed under
-the Apache License, Version 2.0.
-
-
------
-Code under:
-src/com/google/javascript/rhino
-test/com/google/javascript/rhino
-
-URL: http://www.mozilla.org/rhino
-Version: 1.5R3, with heavy modifications
-License: Netscape Public License and MPL / GPL dual license
-
-Description: A partial copy of Mozilla Rhino. Mozilla Rhino is an
-implementation of JavaScript for the JVM. The JavaScript parser and
-the parse tree data structures were extracted and modified
-significantly for use by Google's JavaScript compiler.
-
-Local Modifications: The packages have been renamespaced. All code not
-relavant to parsing has been removed. A JSDoc parser and static typing
-system have been added.
-
-
------
-Code in:
-lib/libtrunk_rhino_parser_jarjared.jar
-
-Rhino
-URL: http://www.mozilla.org/rhino
-Version: Trunk
-License: Netscape Public License and MPL / GPL dual license
-
-Description: Mozilla Rhino is an implementation of JavaScript for the JVM.
-
-Local Modifications: None. We've used JarJar to renamespace the code
-post-compilation. See:
-http://code.google.com/p/jarjar/
-
-
------
-Code in:
-lib/args4j.jar
-
-Args4j
-URL: https://args4j.dev.java.net/
-Version: 2.0.12
-License: MIT
-
-Description:
-args4j is a small Java class library that makes it easy to parse command line
-options/arguments in your CUI application.
-
-Local Modifications: None.
-
-
------
-Code in:
-lib/guava.jar
-
-Guava Libraries
-URL: http://code.google.com/p/guava-libraries/
-Version: R7
-License: Apache License 2.0
-
-Description: Google's core Java libraries.
-
-Local Modifications: None.
-
-
------
-Code in:
-lib/jsr305.jar
-
-Annotations for software defect detection
-URL: http://code.google.com/p/jsr-305/
-Version: svn revision 47
-License: BSD License
-
-Description: Annotations for software defect detection.
-
-Local Modifications: None.
-
-
-----
-Code in:
-lib/junit.jar
-
-JUnit
-URL: http://sourceforge.net/projects/junit/
-Version: 4.8.2
-License: Common Public License 1.0
-
-Description: A framework for writing and running automated tests in Java.
-
-Local Modifications: None.
-
-
----
-Code in:
-lib/protobuf-java.jar
-
-Protocol Buffers
-URL: http://code.google.com/p/protobuf/
-Version: 2.3.0
-License: New BSD License
-
-Description: Supporting libraries for protocol buffers,
-an encoding of structured data.
-
-Local Modifications: None
-
-
----
-Code in:
-lib/ant.jar
-lib/ant-launcher.jar
-
-URL: http://ant.apache.org/bindownload.cgi
-Version: 1.8.1
-License: Apache License 2.0
-Description:
- Ant is a Java based build tool. In theory it is kind of like "make"
- without make's wrinkles and with the full portability of pure java code.
-
-Local Modifications: None
-
-
----
-Code in:
-lib/json.jar
-URL: http://json.org/java/index.html
-Version: JSON version 20090211
-License: MIT license
-Description:
-JSON is a set of java files for use in transmitting data in JSON format.
-
-Local Modifications: None
-
----
-Code in:
-tools/maven-ant-tasks-2.1.1.jar
-URL: http://maven.apache.org
-Version 2.1.1
-License: Apache License 2.0
-Description:
- Maven Ant tasks are used to manage dependencies and to install/deploy to
- maven repositories.
-
-Local Modifications: None
diff --git a/closure-compiler/compiler.jar b/closure-compiler/compiler.jar
deleted file mode 100644
index 10516dc7..00000000
Binary files a/closure-compiler/compiler.jar and /dev/null differ
diff --git a/cut-release.sh b/cut-release.sh
deleted file mode 100755
index 5e339a6e..00000000
--- a/cut-release.sh
+++ /dev/null
@@ -1,194 +0,0 @@
-#!/bin/bash
-
-function help_and_exit() {
- echo "Usage: $0 [-go] [-verbose] [-force]"
- echo
- echo "Moves minified CSS and JS to distribution directories and"
- echo "creates a branch in SVN."
- echo
- echo " -go: Run commands instead of just echoing them."
- echo " -verbose: More verbose logging."
- echo " -force: Ignore sanity checks for testing."
- echo " Incompatible with -go."
- exit "$1"
-}
-
-# 1 for verbose logging
-export VERBOSE="0"
-# 1 if commands that have side-effects should actually be run instead of logged
-export EFFECT="0"
-# 1 to not exit on panic.
-export NO_PANIC="0"
-
-function panic() {
- echo "PANIC: $*"
-
- if ! (( $NO_PANIC )); then
- exit -1
- fi
-}
-
-function command() {
- if (( $VERBOSE )) || ! (( $EFFECT )); then
- echo '$' "$*"
- fi
- if (( $EFFECT )); then
- "$@" || panic "command failed: $@"
- fi
-}
-
-function mime_for_file() {
- local path="$1"
- case "${path##*.}" in
- js) echo -n "text/javascript;charset=UTF-8";;
- css) echo -n "text/css;charset=UTF-8";;
- html) echo -n "text/html;charset=UTF-8";;
- *) panic "unrecognized extension for $path";;
- esac
-}
-
-for var in "$@"; do
- case "$var" in
- -verbose)
- VERBOSE="1"
- ;;
- -go)
- EFFECT="1"
- ;;
- -force)
- NO_PANIC="1"
- ;;
- -h)
- help_and_exit 0
- ;;
- *)
- echo "Unrecognized variable $var"
- help_and_exit -1
- ;;
- esac
-done
-
-if (( $NO_PANIC )) && (( $EFFECT )); then
- NO_PANIC="0"
- panic "-force is incompatible with -go"
-fi
-
-# Find svn root
-export VERSION_BASE="$(
- pushd "$(dirname "$0")/.." > /dev/null; pwd; popd > /dev/null)"
-
-if [ -z "$VERSION_BASE" ] || ! [ -d "$VERSION_BASE" ]; then
- panic "unknown VERSION_BASE"
-fi
-if ! [ -d "$VERSION_BASE/trunk" ]; then
- panic "missing trunk in $VERSION_BASE"
-fi
-if ! [ -d "$VERSION_BASE/loader" ]; then
- panic "missing loader in $VERSION_BASE"
-fi
-if ! [ -d "$VERSION_BASE/branches" ]; then
- panic "missing branches in $VERSION_BASE"
-fi
-
-if (( $VERBOSE )); then
- echo "VERSION_BASE=$VERSION_BASE"
-fi
-
-# Choose a release label
-export RELEASE_LABEL="$(date -u +release-%e-%b-%Y)"
-
-if (( $VERBOSE )); then
- echo "RELEASE_LABEL=$RELEASE_LABEL"
-fi
-
-if [ -e "$VERSION_BASE/branches/$RELEASE_LABEL" ]; then
- panic "duplicate release $VERSION_BASE/branches/$RELEASE_LABEL"
-fi
-
-
-# Make the distribution
-function build() {
- pushd "$VERSION_BASE/trunk" > /dev/null
- make distrib
- local status=$?
- popd > /dev/null
- (($status))
-}
-if build; then
- panic "Make failed"
-fi
-
-if [ -n "$(svn stat "$VERSION_BASE/trunk")" ]; then
- svn stat "$VERSION_BASE/trunk"
- panic "Uncommitted changes"
-fi
-
-function sync() {
- local action="$1"
- local src_dir="$2"
- local dest_dir="$3"
- shift 3
- local exts=$@
- local ext
- local src_file
- local dest_file
- (
- shopt -s nullglob
- for ext in $exts; do
- for src_file in "$src_dir"/*."$ext"; do
- dest_file="$dest_dir"/"$(basename "$src_file")"
- if ! [ -e "$dest_file" ] || \
- diff -q "$src_file" "$dest_file"; then
- "$action" "$src_file" "$dest_file"
- fi
- done
- for dest_file in "$dest_dir"/*."$ext"; do
- src_file="$src_dir"/"$(basename "$dest_file")"
- if ! [ -e "$src_file" ]; then
- "$action" "$src_file" "$dest_file"
- fi
- done
- done
- )
-}
-
-function svn_sync() {
- local src_file="$1"
- local dest_file="$2"
- if ! [ -e "$src_file" ]; then
- command svn delete "$dest_file"
- else
- if [ -e "$dest_file" ]; then
- command cp "$src_file" "$dest_file"
- else
- command cp "$src_file" "$dest_file"
- command svn add "$dest_file"
- command svn propset svn:mime-type "$(mime_for_file "$src_file")" \
- "$dest_file"
- fi
- fi
-}
-
-# Deploy the current compiled source to /loader
-sync svn_sync "$VERSION_BASE/trunk/distrib/google-code-prettify" \
- "$VERSION_BASE/loader" js css
-sync svn_sync "$VERSION_BASE/trunk/styles" \
- "$VERSION_BASE/loader/skins" css
-
-# Cut branch
-command svn copy "$VERSION_BASE/trunk" "$VERSION_BASE/branches/$RELEASE_LABEL"
-
-# Dump final instructions for caller.
-echo
-if (( $EFFECT )); then
- echo "Finally run"
- echo " $ svn commit -m 'Release $RELEASE_LABEL'"
- echo "to commit the new release then upload"
- echo " $VERSION_BASE/trunk/distrib/prettify-small.*"
- echo "to"
- echo " http://code.google.com/p/google-code-prettify/downloads/list"
-else
- echo "Rerun with -go flag to actually execute these commands."
-fi
-
-exit 0
diff --git a/distrib/prettify-small.zip b/distrib/prettify-small.zip
new file mode 100644
index 00000000..c63da471
Binary files /dev/null and b/distrib/prettify-small.zip differ
diff --git a/docs/getting_started.md b/docs/getting_started.md
new file mode 100644
index 00000000..81221bfe
--- /dev/null
+++ b/docs/getting_started.md
@@ -0,0 +1,138 @@
+# 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 `` elements with the
+*prettyprint* class, and adds ``s to colorize keywords, strings,
+comments, and other token types.
+
+```HTML
+
+source code here
+
+```
+
+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://raw.githack.com/google/code-prettify/master/examples/quine.html)
+
+## Auto-Loader
+
+You can load the JavaScript and CSS for prettify via one URL:
+
+```HTML
+
+```
+
+This 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 |
+| --------------------- | ------- | ------------------------------ |
+| autorun=(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](../src). If specified multiple times (`?lang=css&lang=ml`) then all are loaded. |
+| skin=... | none | See the [skin gallery](https://raw.githack.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
+
+```
+
+The above specifies the `lang` parameter to also load the CSS language
+extension and the `skin` parameter to load the
+[*sunburst*](https://raw.githack.com/google/code-prettify/master/styles/index.html#sunburst)
+skin.
+
+## Serving your own JS & CSS
+
+You can
+[download](https://github.com/google/code-prettify/raw/master/distrib/prettify-small.zip)
+the scripts and styles and serve them yourself. Make sure to include both the
+script and a stylesheet:
+
+```HTML
+
+
+```
+
+Then run the `PR.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://raw.githack.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.
+
+For example, set the `lang-scm` hint to specify that the code is Scheme code:
+
+```HTML
+(friends 'of '(parentheses))
+```
+
+It can also be specified as:
+
+```HTML
+
+(friends 'of '(parentheses))
+```
+
+## Line Numbering
+
+```HTML
+
+Many
+lines
+of
+code
+
+```
+
+The `linenums` class in the above code tells the prettyprinter to insert an
+`` element and `- ` elements around each line so that you get line
+numbers.
+
+Most stylesheets then hide the line numbers except for every fifth line.
+
+The class `linenums:40` makes line numbering start at line 40 if you're
+excerpting a larger chunk of code. The following also works:
+
+```HTML
+
+
lots of code
+```
diff --git a/examples/quine.html b/examples/quine.html
new file mode 100644
index 00000000..d43eb11e
--- /dev/null
+++ b/examples/quine.html
@@ -0,0 +1,65 @@
+
+
+
+
+Making Quines Prettier
+
+
+
+
+
+
+Making Quines Prettier
+
+
+Below is the content of this page prettified. The <pre>
+element is prettified because it has class="prettyprint"
and
+because the sourced script loads a JavaScript library that styles source
+code.
+
+
+
+The line numbers to the left appear because the preceding comment
+<?prettify lang=html linenums=true?>
turns on
+line-numbering and the
+stylesheet
+(see skin=sunburst
in the <script src>
)
+specifies that every fifth line should be numbered.
+
+
+
+
+
+
+
+
+
+
diff --git a/js-modules/defs.js b/js-modules/defs.js
new file mode 100644
index 00000000..18f3e4aa
--- /dev/null
+++ b/js-modules/defs.js
@@ -0,0 +1,55 @@
+/**
+ * @typedef {!Array.}
+ * Alternating indices and the decorations that should be inserted there.
+ * The indices are monotonically increasing.
+ */
+var DecorationsT;
+
+/**
+ * @typedef {!{
+ * sourceNode: !Element,
+ * pre: !(number|boolean),
+ * langExtension: ?string,
+ * numberLines: ?(number|boolean),
+ * sourceCode: ?string,
+ * spans: ?(Array.),
+ * basePos: ?number,
+ * decorations: ?DecorationsT
+ * }}
+ *
+ * - sourceNode
- the element containing the source
+ *
- sourceCode
- source as plain text
+ *
- pre
- truthy if white-space in text nodes
+ * should be considered significant.
+ *
- spans
- alternating span start indices into source
+ * and the text node or element (e.g. {@code
}) corresponding to that
+ * span.
+ * - decorations
- an array of style classes preceded
+ * by the position at which they start in job.sourceCode in order
+ *
- basePos
- integer position of this.sourceCode in the larger chunk of
+ * source.
+ *
+ */
+var JobT;
+
+/**
+ * @typedef {!{
+ * sourceCode: string,
+ * spans: !(Array.)
+ * }}
+ *
+ * - sourceCode
- source as plain text
+ *
- spans
- alternating span start indices into source
+ * and the text node or element (e.g. {@code
}) corresponding to that
+ * span.
+ *
+ */
+var SourceSpansT;
+
+/** @define {boolean} */
+/* @ifndef RUN_PRETTIFY */
+var IN_GLOBAL_SCOPE = true;
+/* @endif */
+/* @ifdef RUN_PRETTIFY */
+var IN_GLOBAL_SCOPE = false;
+/* @endif */
diff --git a/js-modules/externs.js b/js-modules/externs.js
index e920098b..d962f53c 100644
--- a/js-modules/externs.js
+++ b/js-modules/externs.js
@@ -1,3 +1,30 @@
+/**
+ * @license
+ * Copyright (C) 2015 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
+ * This file allows separate compilation of language handlers and the
+ * core library.
+ * @externs
+ */
+
+
var PR = {};
/**
@@ -35,3 +62,4 @@ PR.PR_SOURCE = 'src';
PR.PR_STRING = 'str';
PR.PR_TAG = 'tag';
PR.PR_TYPE = 'typ';
+
diff --git a/js-modules/extractSourceSpans.js b/js-modules/extractSourceSpans.js
index 5654cef5..220ae0f2 100644
--- a/js-modules/extractSourceSpans.js
+++ b/js-modules/extractSourceSpans.js
@@ -39,9 +39,9 @@
*
*
* @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.
+ * @param {boolean|number} isPreformatted truthy if white-space in
+ * text nodes should be considered significant.
+ * @return {SourceSpansT} source code and the nodes in which they occur.
*/
function extractSourceSpans(node, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
diff --git a/js-modules/extractSourceSpans_test.html b/js-modules/extractSourceSpans_test.html
deleted file mode 100644
index 090f6e2b..00000000
--- a/js-modules/extractSourceSpans_test.html
+++ /dev/null
@@ -1,129 +0,0 @@
-
-
-Extract Source Spans Test
-
-
-
-
-
-
-Extract Source Spans Test
-
-
- Test space preserved in PRE
-
- print 'Hello '
+ '<World>';
- ^print ^'Hello '^\n^ + '<World>';^
-
- Test class="nocode"
-
- 1. print 'Hello '
2. + '<World>';
- ^print ^'Hello '^\n^ + '<World>';^
-
- Test whitespace normalized in code
-
- print 'Hello '
- + '<World>';
- ^print ^'Hello ' + '<World>';^
-
- Test XMP
-
- print 'Hello '
- + '';
- ^print 'Hello '\n + '<World>';^
-
- Test tabs
-
- print 'Hello '
- + '<World>';
- ^print 'Hello '\n\t+ '<World>';^
-
- Test number lines output
-
- - print 'Hello '
- + '<World>';
- ^print ^'Hello '^\n^ + '<World>';^^
-
-
-
-
-
-
-
- Last modified: Tue Mar 29 16:38:23 PDT 2011
-
diff --git a/js-modules/js_include.pl b/js-modules/js_include.pl
deleted file mode 100644
index 8d3b6238..00000000
--- a/js-modules/js_include.pl
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/perl
-
-# Given a JS file looks for lines like
-# include("path/to/file/to/include");
-# and replaces them with the quoted file relative to the js-modules directory.
-# If the included file ends with ".pl" then it is treated as a perl file to
-# execute and the stdout is used as the JS to include.
-
-use strict;
-
-# Closure Compiler @define annotations that need to be pulled out of included
-# files because @defines need to be top-level vars.
-my $global_defs = "";
-
-# Find @defines at the top of a JS file by pulling off comments and looking for
-# comments containing @define followed by a var declaration.
-sub extractGlobalDefs($) {
- my @headerComments;
- my $s = shift;
- while ($s) {
- last unless $s =~ m#^\s*(?://[^\r\n]*|/\*.*?\*/[ \t]*)[\r\n]*#s;
- my $comment = $&;
- $s = $';
- if ($comment =~ /[\@]define/ && $s =~ /^\s*var\s+[^;]+;[ \t]*[\r\n]*/) {
- my $global = $&;
- $s = $';
- $global =~ s/(var\s*IN_GLOBAL_SCOPE\s*=\s*)true\b/$1false/;
- $global_defs .= "$comment$global";
- } else {
- push(@headerComments, $comment);
- }
- }
- return (join "", @headerComments) . $s;
-}
-
-# readInclude(whiteSpacePrefix, path) returns the JS content at path
-# (with the ".pl" adjustment above) and prepends each line with the
-# whitespace in whiteSpacePrefix to produce a chunk of JS that matches the
-# indentation of the including file.
-# @defines are extracted so that they can all appear globally at the top of
-# the file.
-sub readInclude($$) {
- my $prefix = shift;
- my $name = "js-modules/" . (shift);
- my $in;
- if ($name =~ /\.pl$/) {
- open($in, "perl $name|") or die "$name: $!";
- } else {
- open($in, "<$name") or die "$name: $!";
- }
- my $buf = "";
- while (<$in>) {
- if (m/(\s*)include\("([^"]+)"\);\s*$/) {
- my $inc = extractGlobalDefs(readInclude("$prefix$1", $2));
- $buf .= $inc;
- } else {
- $buf .= "$prefix$_";
- }
- }
- close($in);
- return $buf;
-}
-
-my $target = shift;
-my $inc = readInclude("", $target);
-my $header = "";
-# Put descriptive top level comments above the grouped @defines.
-if ($inc =~ s#^(?://[^\r\n]*|/\*.*?\*/|\s)+##s) {
- $header = $&;
-}
-my $globals = $global_defs;
-# Un-indent @defines.
-$globals =~ s#^[ \t]*##gm;
-$globals .= "\n" unless $globals eq "";
-
-print "$header$globals$inc";
diff --git a/js-modules/node_prettify.js b/js-modules/node_prettify.js
new file mode 100644
index 00000000..7262a48e
--- /dev/null
+++ b/js-modules/node_prettify.js
@@ -0,0 +1,16 @@
+
+var IN_GLOBAL_SCOPE = false;
+
+/* @include prettify.js */
+
+var path = require('path');
+
+module.exports = {
+ prettyPrint: prettyPrint,
+ prettyPrintOne: prettyPrintOne,
+ // include paths for css preprocessor support
+ includePaths: [
+ __dirname,
+ path.resolve(__dirname, '../styles')
+ ]
+};
diff --git a/js-modules/numberLines.js b/js-modules/numberLines.js
index 840fe0be..e7ee3a42 100644
--- a/js-modules/numberLines.js
+++ b/js-modules/numberLines.js
@@ -6,10 +6,14 @@
* HTMLOListElement, and each line is moved into a separate list item.
* This requires cloning elements, so the input might not have unique
* IDs after numbering.
+ * @param {number|null|boolean} startLineNum
+ * If truthy, coerced to an integer which is the 1-indexed line number
+ * of the first line of code. The number of the first line will be
+ * attached to the list.
* @param {boolean} isPreformatted true iff white-space in text nodes should
* be treated as significant.
*/
-function numberLines(node, opt_startLineNum, isPreformatted) {
+function numberLines(node, startLineNum, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var lineBreak = /\r\n?|\n/;
@@ -26,7 +30,7 @@ function numberLines(node, opt_startLineNum, isPreformatted) {
function walk(node) {
var type = node.nodeType;
if (type == 1 && !nocode.test(node.className)) { // Element
- if ('br' === node.nodeName) {
+ if ('br' === node.nodeName.toLowerCase()) {
breakAfter(node);
// Discard the
since it is now flush against a .
if (node.parentNode) {
@@ -110,13 +114,13 @@ function numberLines(node, opt_startLineNum, isPreformatted) {
}
// Make sure numeric indices show correctly.
- if (opt_startLineNum === (opt_startLineNum|0)) {
- listItems[0].setAttribute('value', opt_startLineNum);
+ if (startLineNum === (startLineNum|0)) {
+ listItems[0].setAttribute('value', startLineNum);
}
var ol = document.createElement('ol');
ol.className = 'linenums';
- var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
+ var offset = Math.max(0, ((startLineNum - 1 /* zero index */)) | 0) || 0;
for (var i = 0, n = listItems.length; i < n; ++i) {
li = listItems[i];
// Stick a class on the LIs so that stylesheets can
@@ -130,4 +134,4 @@ function numberLines(node, opt_startLineNum, isPreformatted) {
}
node.appendChild(ol);
-}
\ No newline at end of file
+}
diff --git a/js-modules/numberLines_test.html b/js-modules/numberLines_test.html
deleted file mode 100644
index a074e014..00000000
--- a/js-modules/numberLines_test.html
+++ /dev/null
@@ -1,119 +0,0 @@
-
-
-Number Lines Test
-
-
-
-
-
-
-Number Lines Test
-
-
- Test Nothing to Split
-
- Hello, World!
- - Hello, World!
-
- Test Normalized Spaces
-
- Hello,
World!
- - Hello,
World!
-
- Test BR
-
- Hello,
World!
- - Hello,
- World!
-
- Test line breaks
-
- Hello,
there
World!
- - Hello,
- there
- World!
-
- Test line breaks with followers
-
- Hello,
there
World!
- - Hello,
- there
- World!
-
- Test nocode
-
- Hello,
there
World!
- - Hello,
- there
World!
-
- Test link
-
- Hello,
there
World!
-
-
- Test blank lines
-
- One
Three
- - One
-
- Three
-
-
-
-
-
-
-
- Last modified: Tue Mar 29 16:44:05 PDT 2011
-
diff --git a/js-modules/prettify.js b/js-modules/prettify.js
index 7c45c4be..872c44b7 100644
--- a/js-modules/prettify.js
+++ b/js-modules/prettify.js
@@ -1,17 +1,19 @@
-// Copyright (C) 2006 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
+/**
+ * @license
+ * Copyright (C) 2006 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
/**
* @fileoverview
@@ -19,7 +21,7 @@
*
*
* For a fairly comprehensive set of languages see the
- * README
+ * 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
@@ -55,15 +57,44 @@
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
-/** @define {boolean} */
-var IN_GLOBAL_SCOPE = true;
+/* @ifndef RUN_PRETTIFY */
+/* @include defs.js */
+/* @endif */
+
+/**
+ * {@type !{
+ * 'createSimpleLexer': function (Array, Array): (function (JobT)),
+ * 'registerLangHandler': function (function (JobT), Array.),
+ * 'PR_ATTRIB_NAME': string,
+ * 'PR_ATTRIB_NAME': string,
+ * 'PR_ATTRIB_VALUE': string,
+ * 'PR_COMMENT': string,
+ * 'PR_DECLARATION': string,
+ * 'PR_KEYWORD': string,
+ * 'PR_LITERAL': string,
+ * 'PR_NOCODE': string,
+ * 'PR_PLAIN': string,
+ * 'PR_PUNCTUATION': string,
+ * 'PR_SOURCE': string,
+ * 'PR_STRING': string,
+ * 'PR_TAG': string,
+ * 'PR_TYPE': string,
+ * 'prettyPrintOne': function (string, string, number|boolean),
+ * 'prettyPrint': function (?function, ?(HTMLElement|HTMLDocument))
+ * }}
+ * @const
+ */
+var PR;
/**
* 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;
+var PR_SHOULD_USE_CONTINUATION = true
+if (typeof window !== 'undefined') {
+ window['PR_SHOULD_USE_CONTINUATION'] = PR_SHOULD_USE_CONTINUATION;
+}
/**
* Pretty print a chunk of code.
@@ -88,37 +119,38 @@ var prettyPrint;
(function () {
- var win = window;
+ var win = (typeof window !== 'undefined') ? 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," +
+ var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
+ "double,enum,extern,float,goto,inline,int,long,register,restrict,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," +
+ var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignas,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," +
+ "mutable,namespace,noexcept,noreturn,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," +
+ "abstract,assert,boolean,byte,extends,finally,final,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 CSHARP_KEYWORDS = [COMMON_KEYWORDS,
+ "abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending," +
+ "dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface," +
+ "internal,into,is,join,let,lock,null,object,out,override,orderby,params," +
+ "partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong," +
+ "unchecked,unsafe,ushort,value,var,virtual,where,yield"];
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"];
+ "abstract,async,await,constructor,debugger,enum,eval,export,from,function," +
+ "get,import,implements,instanceof,interface,let,null,of,set,undefined," +
+ "var,with,yield,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";
@@ -130,15 +162,12 @@ var prettyPrint;
"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/;
+ CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS, JSCRIPT_KEYWORDS,
+ PERL_KEYWORDS, PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
+ var C_TYPES = /^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
@@ -210,23 +239,35 @@ var prettyPrint;
*/
var PR_NOCODE = 'nocode';
- include("regexpPrecederPatterns.pl");
+ /* @include regexpPrecederPatterns.js */
- include("combinePrefixPatterns.js");
+ /* @include combinePrefixPatterns.js */
- include("extractSourceSpans.js");
+ /* @include extractSourceSpans.js */
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
+ * @param {!Element} sourceNode
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
+ * @param {string} sourceCode
+ * @param {function(JobT)} langHandler
+ * @param {DecorationsT} out
*/
- function appendDecorations(basePos, sourceCode, langHandler, out) {
+ function appendDecorations(
+ sourceNode, basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
+ /** @type {JobT} */
var job = {
+ sourceNode: sourceNode,
+ pre: 1,
+ langExtension: null,
+ numberLines: null,
sourceCode: sourceCode,
- basePos: basePos
+ spans: null,
+ basePos: basePos,
+ decorations: null
};
langHandler(job);
out.push.apply(out, job.decorations);
@@ -301,8 +342,8 @@ var prettyPrint;
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
- * @return {function (Object)} a
- * function that takes source code and returns a list of decorations.
+ * @return {function (JobT)} a function that takes an undecorated job and
+ * attaches a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
@@ -333,22 +374,19 @@ var prettyPrint;
var nPatterns = fallthroughStylePatterns.length;
/**
- * Lexes job.sourceCode and produces an output array job.decorations of
+ * Lexes job.sourceCode and attaches an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
- * @param {Object} job an object like {
- * sourceCode: {string} sourceText plain text,
- * basePos: {int} position of job.sourceCode in the larger chunk of
- * sourceCode.
- * }
+ * @type{function (JobT)}
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
+ var sourceNode = job.sourceNode;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
- * @type {Array.}
+ * @type {DecorationsT}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
@@ -411,17 +449,20 @@ var prettyPrint;
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
+ sourceNode,
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
+ sourceNode,
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
+ sourceNode,
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
@@ -444,8 +485,9 @@ var prettyPrint;
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
- * @return {function (Object)} a function that examines the source code
- * in the input job and builds the decoration list.
+ * @return {function (JobT)} a function that examines the source code
+ * in the input job and builds a decoration list which it attaches to
+ * the job.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
@@ -497,7 +539,18 @@ var prettyPrint;
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
- if (options['regexLiterals']) {
+ var regexLiterals = options['regexLiterals'];
+ if (regexLiterals) {
+ /**
+ * @const
+ */
+ var regexExcls = regexLiterals > 1
+ ? '' // Multiline regex literals
+ : '\n\r';
+ /**
+ * @const
+ */
+ var regexAny = regexExcls ? '.' : '[\\S\\s]';
/**
* @const
*/
@@ -505,18 +558,19 @@ var prettyPrint;
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
- '/(?=[^/*])'
+ '/(?=[^/*' + regexExcls + '])'
// and then contains any number of raw characters,
- + '(?:[^/\\x5B\\x5C]'
+ + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
// escape sequences (\x5C),
- + '|\\x5C[\\s\\S]'
+ + '|\\x5C' + regexAny
// or non-nesting character sets (\x5B\x5D);
- + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
+ + '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
+ + '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
- new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
+ RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
@@ -543,7 +597,7 @@ var prettyPrint;
// which are the following plus space, tab, and newline: { }
// | & $ ; < >
// ...
-
+
// A word beginning with # causes that word and all remaining
// characters on that line to be ignored.
@@ -571,7 +625,10 @@ var prettyPrint;
// If that does turn out to be a problem, we should change the below
// when hc is truthy to include # in the run of punctuation characters
// only when not followint [|&;<>].
- /^.[^\s\w\.$@\'\"\`\/\\]*/;
+ '^.[^\\s\\w.$@\'"`/\\\\]*';
+ if (options['regexLiterals']) {
+ punctuation += '(?!\s*\/)';
+ }
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
@@ -591,9 +648,10 @@ var prettyPrint;
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
- // Don't treat escaped quotes in bash as starting strings. See issue 144.
+ // Don't treat escaped quotes in bash as starting strings.
+ // See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
- [PR_PUNCTUATION, punctuation, null]);
+ [PR_PUNCTUATION, new RegExp(punctuation), null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
@@ -606,26 +664,16 @@ var prettyPrint;
'regexLiterals': true
});
- include("numberLines.js");
+ /* @include numberLines.js */
- include("recombineTagsAndDecorations.js");
+ /* @include recombineTagsAndDecorations.js */
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
- * @param {function (Object)} handler a function from source code to a list
+ * @param {function (JobT)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
- * state of the computation. The single parameter has the form
- * {@code {
- * sourceCode: {string} as plain text.
- * decorations: {Array.} an array of style classes
- * preceded by the position at which they start in
- * job.sourceCode in order.
- * The language handler should assigned this field.
- * basePos: {int} the position of source in the larger source chunk.
- * All positions in the output decorations array are relative
- * to the larger source chunk.
- * } }
+ * state of the computation and attaches the decorations to it.
* @param {Array.} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
@@ -724,7 +772,7 @@ var prettyPrint;
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
- 'regexLiterals': true
+ 'regexLiterals': 2 // multiline regex literals
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
@@ -736,7 +784,7 @@ var prettyPrint;
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
- }), ['javascript', 'js']);
+ }), ['javascript', 'js', 'ts', 'typescript']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
@@ -745,14 +793,10 @@ var prettyPrint;
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
- registerLangHandler(sourceDecorator({
- 'keywords': RUST_KEYWORDS,
- 'cStyleComments': true,
- 'multilineStrings': true
- }), ['rc', 'rs', 'rust']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
+ /** @param {JobT} job */
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
@@ -773,7 +817,7 @@ var prettyPrint;
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
- console['log'](e && e['stack'] ? e['stack'] : e);
+ console['log'](e && e['stack'] || e);
}
}
}
@@ -787,6 +831,11 @@ var prettyPrint;
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
+ /** @type{number|boolean} */
+ var nl = opt_numberLines || false;
+ /** @type{string|null} */
+ var langExtension = opt_langExtension || null;
+ /** @type{!Element} */
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g.
.
@@ -796,16 +845,21 @@ var prettyPrint;
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '' + sourceCodeHtml + '
';
- container = container.firstChild;
- if (opt_numberLines) {
- numberLines(container, opt_numberLines, true);
+ container = /** @type{!Element} */(container.firstChild);
+ if (nl) {
+ numberLines(container, nl, true);
}
+ /** @type{JobT} */
var job = {
- langExtension: opt_langExtension,
- numberLines: opt_numberLines,
+ langExtension: langExtension,
+ numberLines: nl,
sourceNode: container,
- pre: 1
+ pre: 1,
+ sourceCode: null,
+ basePos: null,
+ spans: null,
+ decorations: null
};
applyDecorator(job);
return container.innerHTML;
@@ -842,7 +896,6 @@ var prettyPrint;
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
- var prettyPrintingJob;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
@@ -850,6 +903,7 @@ var prettyPrint;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
+ var EMPTY = {};
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
@@ -857,8 +911,34 @@ var prettyPrint;
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
+
+ // Look for a preceding comment like
+ //
+ var attrs = EMPTY;
+ {
+ for (var preceder = cs; (preceder = preceder.previousSibling);) {
+ var nt = preceder.nodeType;
+ // is parsed by HTML 5 to a comment node (8)
+ // like , but in XML is a processing instruction
+ var value = (nt === 7 || nt === 8) && preceder.nodeValue;
+ if (value
+ ? !/^\??prettify\b/.test(value)
+ : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
+ // Skip over white-space text nodes but not others.
+ break;
+ }
+ if (value) {
+ attrs = {};
+ value.replace(
+ /\b(\w+)=([\w:.%+-]+)/g,
+ function (_, name, value) { attrs[name] = value; });
+ break;
+ }
+ }
+ }
+
var className = cs.className;
- if (prettyPrintRe.test(className)
+ if ((attrs !== EMPTY || prettyPrintRe.test(className))
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
@@ -887,15 +967,18 @@ var prettyPrint;
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
- var langExtension = className.match(langExtensionRe);
- // Support
- var wrapper;
- if (!langExtension && (wrapper = childContentWrapper(cs))
- && codeRe.test(wrapper.tagName)) {
- langExtension = wrapper.className.match(langExtensionRe);
- }
+ var langExtension = attrs['lang'];
+ if (!langExtension) {
+ langExtension = className.match(langExtensionRe);
+ // Support
+ var wrapper;
+ if (!langExtension && (wrapper = childContentWrapper(cs))
+ && codeRe.test(wrapper.tagName)) {
+ langExtension = wrapper.className.match(langExtensionRe);
+ }
- if (langExtension) { langExtension = langExtension[1]; }
+ if (langExtension) { langExtension = langExtension[1]; }
+ }
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
@@ -917,18 +1000,27 @@ var prettyPrint;
// Look for a class like linenums or linenums: where is the
// 1-indexed number of the first line.
- var lineNums = cs.className.match(/\blinenums\b(?::(\d+))?/);
- lineNums = lineNums
- ? lineNums[1] && lineNums[1].length ? +lineNums[1] : true
+ var lineNums = attrs['linenums'];
+ if (!(lineNums = lineNums === 'true' || +lineNums)) {
+ lineNums = className.match(/\blinenums\b(?::(\d+))?/);
+ lineNums =
+ lineNums
+ ? lineNums[1] && lineNums[1].length
+ ? +lineNums[1] : true
: false;
+ }
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
- prettyPrintingJob = {
+ var prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
- pre: preformatted
+ pre: preformatted,
+ sourceCode: null,
+ basePos: null,
+ spans: null,
+ decorations: null
};
applyDecorator(prettyPrintingJob);
}
@@ -936,7 +1028,7 @@ var prettyPrint;
}
if (k < elements.length) {
// finish up in a continuation
- setTimeout(doWork, 250);
+ win.setTimeout(doWork, 250);
} else if ('function' === typeof opt_whenDone) {
opt_whenDone();
}
@@ -970,7 +1062,7 @@ var prettyPrint;
IN_GLOBAL_SCOPE
? (win['prettyPrintOne'] = $prettyPrintOne)
: (prettyPrintOne = $prettyPrintOne),
- 'prettyPrint': prettyPrint =
+ 'prettyPrint':
IN_GLOBAL_SCOPE
? (win['prettyPrint'] = $prettyPrint)
: (prettyPrint = $prettyPrint)
@@ -988,9 +1080,10 @@ var prettyPrint;
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
+ var define = win['define'];
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
- return PR;
+ return PR;
});
}
})();
diff --git a/js-modules/recombineTagsAndDecorations.js b/js-modules/recombineTagsAndDecorations.js
index 33a8fb3f..69b1a8f0 100644
--- a/js-modules/recombineTagsAndDecorations.js
+++ b/js-modules/recombineTagsAndDecorations.js
@@ -1,14 +1,7 @@
/**
* Breaks {@code job.sourceCode} around style boundaries in
* {@code job.decorations} and modifies {@code job.sourceNode} in place.
- * @param {Object} job like {
- * sourceCode: {string} source as plain text,
- * spans: {Array.} alternating span start indices into source
- * and the text node or element (e.g. {@code
}) corresponding to that
- * span.
- * decorations: {Array.
+ * @param {JobT} job
* @private
*/
function recombineTagsAndDecorations(job) {
@@ -62,7 +55,7 @@ function recombineTagsAndDecorations(job) {
nDecorations = decorations.length = decPos;
var sourceNode = job.sourceNode;
- var oldDisplay;
+ var oldDisplay = "";
if (sourceNode) {
oldDisplay = sourceNode.style.display;
sourceNode.style.display = 'none';
@@ -71,13 +64,14 @@ function recombineTagsAndDecorations(job) {
var decoration = null;
while (spanIndex < nSpans) {
var spanStart = spans[spanIndex];
- var spanEnd = spans[spanIndex + 2] || sourceLength;
+ var spanEnd = /** @type{number} */ (spans[spanIndex + 2])
+ || sourceLength;
var decEnd = decorations[decorationIndex + 2] || sourceLength;
var end = Math.min(spanEnd, decEnd);
- var textNode = spans[spanIndex + 1];
+ var textNode = /** @type{Node} */ (spans[spanIndex + 1]);
var styledText;
if (textNode.nodeType !== 1 // Don't muck with
s or - s
// Don't introduce spans around empty text nodes.
diff --git a/js-modules/recombineTagsAndDecorations_test.html b/js-modules/recombineTagsAndDecorations_test.html
deleted file mode 100644
index 555ee3c6..00000000
--- a/js-modules/recombineTagsAndDecorations_test.html
+++ /dev/null
@@ -1,98 +0,0 @@
-
-
-
Recombine Tags And Decorations
-
-
-
-
-
-
-
-
-
-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
-
diff --git a/js-modules/regexpPrecederPatterns.js b/js-modules/regexpPrecederPatterns.js
new file mode 100644
index 00000000..65d3de53
--- /dev/null
+++ b/js-modules/regexpPrecederPatterns.js
@@ -0,0 +1,30 @@
+
+// Regex pattern below is automatically generated by regexpPrecederPatterns.pl
+// Do not modify, your changes will be erased.
+
+// 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.
+
+/**
+ * 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*';
diff --git a/js-modules/regexpPrecederPatterns.pl b/js-modules/regexpPrecederPatterns.pl
index 488dbd68..0f1e1d59 100644
--- a/js-modules/regexpPrecederPatterns.pl
+++ b/js-modules/regexpPrecederPatterns.pl
@@ -1,6 +1,14 @@
use strict;
print "
+// Regex pattern below is automatically generated by regexpPrecederPatterns.pl
+// Do not modify, your changes will be erased.
+
+// 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.
/**
* A set of tokens that can precede a regular expression literal in
@@ -9,12 +17,12 @@
* 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
+ * 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
+ * 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.
*
@@ -34,7 +42,7 @@
"->",
"\\/=?", # "/", "/=",
"::?", # ":", "::",
- "<=?", # "<", "<<", "<<=", "<=",
+ "<=?", # "<", "<<", "<<=", "<=",
">>?>?=?", # ">", ">=", ">>", ">>=", ">>>", ">>>=",
",",
";", # ";"
@@ -58,11 +66,3 @@
$pattern .= ")\\\\s*'"; # matches at end, and matches empty string
print "$pattern;\n";
-
-print "
-// CAVEAT: this does not properly handle the case where a regular
-// expression immediately follows another since a regular expression may
-// have flags for case-sensitivity and the like. Having regexp tokens
-// adjacent is not valid in any language I'm aware of, so I'm punting.
-// TODO: maybe style special characters inside a regexp as punctuation.
-";
diff --git a/js-modules/run_prettify.js b/js-modules/run_prettify.js
index 1a283186..faae9897 100644
--- a/js-modules/run_prettify.js
+++ b/js-modules/run_prettify.js
@@ -1,64 +1,69 @@
-// Copyright (C) 2013 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-
-// Looks at query parameters to decide which language handlers and style-sheets
-// to load.
-
-// Query Parameter Format Effect Default
-// +------------------+---------------+------------------------------+--------+
-// | autorun= | true | false | If true then prettyPrint() | "true" |
-// | | | is called on page load. | |
-// +------------------+---------------+------------------------------+--------+
-// | lang= | language name | Loads the language handler | Can |
-// | | | named "lang-.js". | appear |
-// | | | See available handlers at | many |
-// | | | http://code.google.com/p/ | times. |
-// | | | google-code-prettify/source/ | |
-// | | | browse/trunk/src | |
-// +------------------+---------------+------------------------------+--------+
-// | skin= | skin name | Loads the skin stylesheet | none. |
-// | | | named ".css". | |
-// | | | http://code.google.com/p/ | |
-// | | | google-code-prettify/source/ | |
-// | | | browse/trunk/styles | |
-// +------------------+---------------+------------------------------+--------+
-// | namespace= | dotted ident | Attaches prettyPrint and | none |
-// | | | related functions to the | |
-// | | | global object at that path | |
-// | | | so they are accessible to | |
-// | | | client code. | |
-// +------------------+---------------+------------------------------+--------+
-// | callback= | JS identifier | When "prettyPrint" finishes | none |
-// | | | window.exports[js_ident] is | |
-// | | | called. | |
-// | | | The callback must be under | |
-// | | | exports to reduce the risk | |
-// | | | of XSS via query parameter | |
-// | | | injection. | |
-// +------------------+---------------+------------------------------+--------+
-
-// Exmaples
-// .../prettify.js?lang=css&skin=sunburst
-// 1. Loads the CSS language handler which can be used to prettify CSS
-// stylesheets, HTML
-
-
+
-
-
+
+
+
+<!doctype html>
+<html>
+<head>
+<title>HTML Test</title>
<script type="text/javascript">
// Say hello world until the user starts questioning
// the meaningfulness of their existence.
@@ -51,11 +94,18 @@
}
}
</script>
-<style>
+<style type="text/css">
p { color: pink }
b { color: blue }
u { color: "umber" }
</style>
+</head>
+<body>
+<h1>Hello world!</h1>
+</body>
+</html>
-
+
+