diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3ffd352d6e..2ab4fdbabc 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -112,7 +112,7 @@
`. Entre la etiqueta `` de apertura y cierre, insertarás el ejemplo de código en cuestión. El principio básico para escribir un buen ejemplo de código para la referencia es mantener las cosas simples y mínimas. El ejemplo debe ser significativo y explicar cómo funciona la función, valga la redundancia, sin ser demasiado complicado. El lienzo para el ejemplo debe ser de 100x100 pixeles y si la función `setup()` no está incluida, como en el ejemplo anterior, el código será envuelto automáticamente en una función `setup()` con un lienzo predeterminado de fondo gris y 100x100 píxeles. No entraremos aquí en detalles sobre buenas prácticas y estilo para los ejemplos de código; consulta la guía de estilo de referencia en su lugar.
+Después de la etiqueta `@example`, debes comenzar con una etiqueta HTML `` seguida de una etiqueta ``. Entre la etiqueta `` de apertura y cierre, insertarás el ejemplo de código en cuestión. El principio básico para escribir un buen ejemplo de código para la referencia es mantener las cosas simples y mínimas. El ejemplo debe set significativo y explicar cómo funciona la función, valga la redundancia, sin set demasiado complicado. El lienzo para el ejemplo debe set de 100x100 pixeles y si la función `setup()` no está incluida, como en el ejemplo anterior, el código será envuelto automáticamente en una función `setup()` con un lienzo predeterminado de fondo gris y 100x100 píxeles. No entraremos aquí en detalles sobre buenas prácticas y estilo para los ejemplos de código; consulta la guía de estilo de referencia en su lugar.
Puedes tener múltiples ejemplos para una función. Para hacerlo agrega un `` y un bloque HTML `` adicionales justo después del primer bloque cerrado, separados por una línea en blanco.
@@ -250,7 +250,7 @@ Si no deseas que la página de referencia ejecute tu código de ejemplo (es deci
*
```
-Si no quieres que el ejemplo se ejecute como parte de las pruebas automatizadas (por ejemplo, si el ejemplo requiere interacción del usuario), incluye la clase "`notest`" en el ``:
+Si no quieres que el ejemplo se ejecute como parte de las pruebas automatizadas (por ejemplo, si el ejemplo require interacción del usuario), incluye la clase "`notest`" en el ``:
```
* @example
@@ -262,11 +262,11 @@ Si no quieres que el ejemplo se ejecute como parte de las pruebas automatizadas
*
```
-Si tu ejemplo utiliza archivos externos como recursos, colócalos en la carpeta [/docs/yuidoc-p5-theme/assets](https://github.com/processing/p5.js/tree/main/docs/yuidoc-p5-theme/assets) (o reutiliza uno que ya esté allí) y luego enlázalos con "assets/nombrearchivo.ext" en el código. Consulta la referencia de [tint()](https://p5js.org/reference/p5/tint) como ejemplo.
+Si tu ejemplo utilize archivos externos como recursos, colócalos en la carpeta [/docs/yuidoc-p5-theme/assets](https://github.com/processing/p5.js/tree/main/docs/yuidoc-p5-theme/assets) (o reutiliza uno que ya esté allí) y luego enlázalos con "assets/nombrearchivo.ext" en el código. Consulta la referencia de [tint()](https://p5js.org/reference/p5/tint) como ejemplo.
### Agregar descripción a un lienzo usando `describe()`
-Por último, para cada ejemplo que añadas, se requiere que utilices la función de p5.js `describe()` en el ejemplo para crear una descripción accesible del lienzo para lectores de pantalla. Incluye sólo un parámetro: una cadena con una breve descripción de lo que está sucediendo en el lienzo.
+Por último, para cada ejemplo que añadas, se require que utilices la función de p5.js `describe()` en el ejemplo para crear una descripción accessible del lienzo para lectores de pantalla. Incluye sólo un parámetro: una cadena con una breve descripción de lo que está sucediendo en el lienzo.
```
* @example
@@ -375,7 +375,7 @@ Los constructores de clases se definen con la etiqueta `@class`y la etiqueta `@c
El repositorio de p5.js está configurado para que puedas generar y previsualizar la referencia sin necesidad de compilar y ejecutar también el sitio web de p5.js.
-- El comando principal para generar la referencia a partir de los comentarios de referencia en el código fuente es el siguiente.
+- El commando principal para generar la referencia a partir de los comentarios de referencia en el código fuente es el siguiente.
```
npm run docs
@@ -383,7 +383,7 @@ npm run docs
Esto generará los archivos de vista previa necesarios y el archivo principal `docs/reference/data.json`, que es el mismo archivo (después de la minificación) que se utilizará para renderizar la página de referencia en el sitio web.
-- Para trabajar continuamente en la referencia, puedes ejecutar el siguiente comando.
+- Para trabajar continuamente en la referencia, puedes ejecutar el siguiente commando.
```
npm run docs:dev
diff --git a/contributor_docs/es/contributor_guidelines.md b/contributor_docs/es/contributor_guidelines.md
index 3b039061ac..70787b88cc 100644
--- a/contributor_docs/es/contributor_guidelines.md
+++ b/contributor_docs/es/contributor_guidelines.md
@@ -6,7 +6,7 @@
Si estás buscando contribuir más allá de los repositorios de p5.js (escribiendo tutoriales, planeando clases, organizando eventos), por favor consulta la documentación correspondiente para este tipo de colaboraciones. Aquellos que sean Supervisores o Responsables de mantenimiento, encontrarán más útil referirse a las [Instrucciones para Supervisores](https://github.com/processing/p5.js/blob/main/contributor_docs/es/steward_guidelines.md) cuando se trata de revisar 'Issues' (problemas) y 'Pull Requests'.
-Este es un documento relativamente largo e integral, pero trataremos de indicar todos los pasos tan claro como sea posible. Utiliza la tabla de contenidos para encontrar las secciones que son relevantes para ti, y siéntete libre de omitir secciones que no son relevantes para las contribuciones que planeas hacer.
+Este es un documento relativamente largo e integral, pero trataremos de indicar todos los pasos tan claro como sea possible. Utilize la tabla de contenidos para encontrar las secciones que son relevantes para ti, y siéntete libre de omitir secciones que no son relevantes para las contribuciones que planeas hacer.
**Si eres un nuevo contribuidor te sugerimos comenzar con la primera sección: “Todo acerca de los 'Issues' (o problemas)”. Si simplemente quieres una configuración paso-a-paso del proceso de desarrollo, puedes dirigirte a la sección de “Inicio Rápido para Desarrolladores”.**
@@ -25,7 +25,7 @@ Este es un documento relativamente largo e integral, pero trataremos de indicar
- [Utilizando la funcionalidad de edición de Github](#utilizando-la-funcionalidad-de-edición-de-github)
- [Haciendo un fork de p5.js y trabajando desde tu fork](#haciendo-un-fork-de-p5js-y-trabajando-desde-tu-fork)
- [Utilizando Github Desktop](#utilizando-github-desktop)
- - [Utilizando la interfaz de línea de comandos de Git](#utilizando-la-interfaz-de-línea-de-comandos-de-git)
+ - [Utilizando la interfaz de línea de commandos de Git](#utilizando-la-interfaz-de-línea-de-commandos-de-git)
- [Desglose de la base de código ](#desglose-de-la-base-de-código)
- [Configuración de compilación](#configuración-de-compilación)
- [Flujo de trabajo de Git](#flujo-de-trabajo-de-git)
@@ -57,11 +57,11 @@ La mayoría de la actividad en los repositorios de GitHub de p5.js (también con

-'Issues' es el nombre común que se le da a una publicación en GitHub que apunta a describir, como lo dice su nombre, un problema. Los Issues pueden ser reportes de error, solicitudes para añadir un nueva funcionalidad, una discusión, o cualquier publicación que se relacione con el desarrollo de la biblioteca de p5.js. Cualquiera con una cuenta de GitHub puede añadir comentarios debajo de cada Issue, ¡incluyendo bots! Este es el lugar donde los contribuidores discuten temas relacionados con el desarrollo del proyecto dentro del repositorio.
+'Issues' es el nombre común que se le da a una publicación en GitHub que apunta a describir, como lo dice su nombre, un problema. Los Issues pueden set reportes de error, solicitudes para añadir un nueva funcionalidad, una discusión, o cualquier publicación que se relacione con el desarrollo de la biblioteca de p5.js. Cualquiera con una cuenta de GitHub puede añadir comentarios debajo de cada Issue, ¡incluyendo bots! Este es el lugar donde los contribuidores discuten temas relacionados con el desarrollo del proyecto dentro del repositorio.
-Mientras un Issue puede ser creado por diferentes razones, usualmente utilizamos la creación de un Issue para discutir el desarrollo del código fuente de p5.js. Temas como la corrección de errores de tu propio código, invitación de colaboradores a tu proyecto, u otros temas no relacionados, deben ser discutidos ya sea en el [foro](https://discourse.processing.com) o en otras plataformas de comunicación como [Discord](https://discord.p5js.org).
+Mientras un Issue puede set creado por diferentes razones, usualmente utilizamos la creación de un Issue para discutir el desarrollo del código fuente de p5.js. Temas como la corrección de errores de tu propio código, invitación de colaboradores a tu proyecto, u otros temas no relacionados, deben set discutidos ya sea en el [foro](https://discourse.processing.com) o en otras plataformas de comunicación como [Discord](https://discord.p5js.org).
-¡Hemos creado plantillas fáciles de usar que puede ayudarte a determinar si un tema es adecuado para ser publicado como un Issue en GitHub, o si sería más apropiado publicarlo en otro lugar!
+¡Hemos creado plantillas fáciles de usar que puede ayudarte a determinar si un tema es adecuado para set publicado como un Issue en GitHub, o si sería más apropiado publicarlo en otro lugar!
## Plantillas para reportar "Issues"
@@ -69,7 +69,7 @@ Las plantillas para reportar Issues en p5.js hacen que sea más sencil

-Para registrar un Issue por primera vez dentro del repositorio de p5.js, haz click en la pestaña que dice "Issues", ubicada en la parte superior. Una vez dentro de la página de "Issues" haz clic en el botón "New Issue" (problema nuevo), que se encuentra al costado derecho. Se te presentarán diferentes opciones de plantilla que te van a dirigir al lugar adecuado para registrar tu Issue. Te recomendamos elegir la plantilla más relevante para tu caso para asegurarte de que tu Issue reciba rápidamente la atención correcta.
+Para registrar un Issue por primera vez dentro del repositorio de p5.js, haz click en la pestaña que dice "Issues", ubicada en la parte superior. Una vez dentro de la página de "Issues" haz clic en el botón "New Issue" (problema nuevo), que se encuentra al costado derecho. Se te presentarán diferentes opciones de plantilla que te van a dirigir al lugar adecuado para registrar tu Issue. Te recomendamos elegir la plantilla más relevant para tu caso para asegurarte de que tu Issue reciba rápidamente la atención correcta.

@@ -77,7 +77,7 @@ Para registrar un Issue por primera vez dentro del repositorio de p5.js
Cuando encuentres un comportamiento incorrecto en p5.js, o algo que no se esté comportando como se ha descrito en la documentación, [usa esta plantilla]( https://github.com/processing/p5.js/issues/new?assignees=&labels=Bug&projects=&template=found-a-bug.yml). Por favor, ten en cuenta que si estás tratado de corregir el código de tu sketch (boceto), y crees que el problema tal vez se encuentra en tu código, primero consulta en el [foro de discusiones]( https://discourse.processing.org/) antes de reportar un error.
-Esta plantilla provee campos que debes llenar con la siguiente información relevante:
+Esta plantilla provee campos que debes llenar con la siguiente información relevant:
1. **¿Cuál es la subárea más adecuada de p5.js?:** esto añadirá automáticamente las [etiquetas]( https://github.com/processing/p5.js/blob/main/contributor_docs/issue_labels.md) relevantes a tu Issue, lo que nos ayudará a identificar y responder adecuadamente.
2. **Versión de p5.js:** Puedes verificar la versión de p5.js dentro de la etiqueta `}\n * define style rules. See the example page for examples.\n * mark the {@code } and {@code } tags in your source with\n * {@code class=prettyprint.}\n * You can also use the (html deprecated) {@code } tag, but the pretty\n * printer needs to do more substantial DOM manipulations to support that, so\n * some css styles may not be preserved.\n * \n * That's it. I wanted to keep the API as simple as possible, so there's no\n * need to specify which language the code is in, but if you wish, you can add\n * another class to the {@code } or {@code } element to specify the\n * language, as in {@code }. Any class that\n * starts with \"lang-\" followed by a file extension, specifies the file type.\n * See the \"lang-*.js\" files in this directory for code that implements\n * per-language file handlers.\n * \n * Change log:
\n * cbeust, 2006/08/22\n *
\n * Java annotations (start with \"@\") are now captured as literals (\"lit\")\n *
\n * @requires console\n */\n\n// JSLint declarations\n/*global console, document, navigator, setTimeout, window, define */\n\n/** @define {boolean} */\nvar IN_GLOBAL_SCOPE = true;\n\n/**\n * Split {@code prettyPrint} into multiple timeouts so as not to interfere with\n * UI events.\n * If set to {@code false}, {@code prettyPrint()} is synchronous.\n */\nwindow['PR_SHOULD_USE_CONTINUATION'] = true;\n\n/**\n * Pretty print a chunk of code.\n * @param {string} sourceCodeHtml The HTML to pretty print.\n * @param {string} opt_langExtension The language name to use.\n * Typically, a filename extension like 'cpp' or 'java'.\n * @param {number|boolean} opt_numberLines True to number lines,\n * or the 1-indexed number of the first line in sourceCodeHtml.\n * @return {string} code as html, but prettier\n */\nvar prettyPrintOne;\n/**\n * Find all the {@code } and {@code } tags in the DOM with\n * {@code class=prettyprint} and prettify them.\n *\n * @param {Function} opt_whenDone called when prettifying is done.\n * @param {HTMLElement|HTMLDocument} opt_root an element or document\n * containing all the elements to pretty print.\n * Defaults to {@code document.body}.\n */\nvar prettyPrint;\n\n\n(function () {\n var win = window;\n // Keyword lists for various languages.\n // We use things that coerce to strings to make them compact when minified\n // and to defeat aggressive optimizers that fold large string constants.\n var FLOW_CONTROL_KEYWORDS = [\"break,continue,do,else,for,if,return,while\"];\n var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,\"auto,case,char,const,default,\" + \n \"double,enum,extern,float,goto,inline,int,long,register,short,signed,\" +\n \"sizeof,static,struct,switch,typedef,union,unsigned,void,volatile\"];\n var COMMON_KEYWORDS = [C_KEYWORDS,\"catch,class,delete,false,import,\" +\n \"new,operator,private,protected,public,this,throw,true,try,typeof\"];\n var CPP_KEYWORDS = [COMMON_KEYWORDS,\"alignof,align_union,asm,axiom,bool,\" +\n \"concept,concept_map,const_cast,constexpr,decltype,delegate,\" +\n \"dynamic_cast,explicit,export,friend,generic,late_check,\" +\n \"mutable,namespace,nullptr,property,reinterpret_cast,static_assert,\" +\n \"static_cast,template,typeid,typename,using,virtual,where\"];\n var JAVA_KEYWORDS = [COMMON_KEYWORDS,\n \"abstract,assert,boolean,byte,extends,final,finally,implements,import,\" +\n \"instanceof,interface,null,native,package,strictfp,super,synchronized,\" +\n \"throws,transient\"];\n var CSHARP_KEYWORDS = [JAVA_KEYWORDS,\n \"as,base,by,checked,decimal,delegate,descending,dynamic,event,\" +\n \"fixed,foreach,from,group,implicit,in,internal,into,is,let,\" +\n \"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,\" +\n \"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,\" +\n \"var,virtual,where\"];\n var COFFEE_KEYWORDS = \"all,and,by,catch,class,else,extends,false,finally,\" +\n \"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,\" +\n \"throw,true,try,unless,until,when,while,yes\";\n var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,\n \"debugger,eval,export,function,get,null,set,undefined,var,with,\" +\n \"Infinity,NaN\"];\n var PERL_KEYWORDS = \"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,\" +\n \"goto,if,import,last,local,my,next,no,our,print,package,redo,require,\" +\n \"sub,undef,unless,until,use,wantarray,while,BEGIN,END\";\n var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"and,as,assert,class,def,del,\" +\n \"elif,except,exec,finally,from,global,import,in,is,lambda,\" +\n \"nonlocal,not,or,pass,print,raise,try,with,yield,\" +\n \"False,True,None\"];\n var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"alias,and,begin,case,class,\" +\n \"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,\" +\n \"rescue,retry,self,super,then,true,undef,unless,until,when,yield,\" +\n \"BEGIN,END\"];\n var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"as,assert,const,copy,drop,\" +\n \"enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,\" +\n \"pub,pure,ref,self,static,struct,true,trait,type,unsafe,use\"];\n var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"case,done,elif,esac,eval,fi,\" +\n \"function,in,local,set,then,until\"];\n var ALL_KEYWORDS = [\n CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,\n PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];\n var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\\d*)\\b/;\n\n // token style names. correspond to css classes\n /**\n * token style for a string literal\n * @const\n */\n var PR_STRING = 'str';\n /**\n * token style for a keyword\n * @const\n */\n var PR_KEYWORD = 'kwd';\n /**\n * token style for a comment\n * @const\n */\n var PR_COMMENT = 'com';\n /**\n * token style for a type\n * @const\n */\n var PR_TYPE = 'typ';\n /**\n * token style for a literal value. e.g. 1, null, true.\n * @const\n */\n var PR_LITERAL = 'lit';\n /**\n * token style for a punctuation string.\n * @const\n */\n var PR_PUNCTUATION = 'pun';\n /**\n * token style for plain text.\n * @const\n */\n var PR_PLAIN = 'pln';\n\n /**\n * token style for an sgml tag.\n * @const\n */\n var PR_TAG = 'tag';\n /**\n * token style for a markup declaration such as a DOCTYPE.\n * @const\n */\n var PR_DECLARATION = 'dec';\n /**\n * token style for embedded source.\n * @const\n */\n var PR_SOURCE = 'src';\n /**\n * token style for an sgml attribute name.\n * @const\n */\n var PR_ATTRIB_NAME = 'atn';\n /**\n * token style for an sgml attribute value.\n * @const\n */\n var PR_ATTRIB_VALUE = 'atv';\n\n /**\n * A class that indicates a section of markup that is not code, e.g. to allow\n * embedding of line numbers within code listings.\n * @const\n */\n var PR_NOCODE = 'nocode';\n\n \n \n /**\n * A set of tokens that can precede a regular expression literal in\n * javascript\n * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html\n * has the full list, but I've removed ones that might be problematic when\n * seen in languages that don't support regular expression literals.\n *\n * Specifically, I've removed any keywords that can't precede a regexp\n * literal in a syntactically legal javascript program, and I've removed the\n * \"in\" keyword since it's not a keyword in many languages, and might be used\n * as a count of inches.\n *\n *
The link above does not accurately describe EcmaScript rules since\n * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works\n * very well in practice.\n *\n * @private\n * @const\n */\n var REGEXP_PRECEDER_PATTERN = '(?:^^\\\\.?|[+-]|[!=]=?=?|\\\\#|%=?|&&?=?|\\\\(|\\\\*=?|[+\\\\-]=|->|\\\\/=?|::?|<=?|>>?>?=?|,|;|\\\\?|@|\\\\[|~|{|\\\\^\\\\^?=?|\\\\|\\\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\\\s*';\n \n // CAVEAT: this does not properly handle the case where a regular\n // expression immediately follows another since a regular expression may\n // have flags for case-sensitivity and the like. Having regexp tokens\n // adjacent is not valid in any language I'm aware of, so I'm punting.\n // TODO: maybe style special characters inside a regexp as punctuation.\n\n /**\n * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally\n * matches the union of the sets of strings matched by the input RegExp.\n * Since it matches globally, if the input strings have a start-of-input\n * anchor (/^.../), it is ignored for the purposes of unioning.\n * @param {Array.} regexs non multiline, non-global regexs.\n * @return {RegExp} a global regex.\n */\n function combinePrefixPatterns(regexs) {\n var capturedGroupIndex = 0;\n \n var needToFoldCase = false;\n var ignoreCase = false;\n for (var i = 0, n = regexs.length; i < n; ++i) {\n var regex = regexs[i];\n if (regex.ignoreCase) {\n ignoreCase = true;\n } else if (/[a-z]/i.test(regex.source.replace(\n /\\\\u[0-9a-f]{4}|\\\\x[0-9a-f]{2}|\\\\[^ux]/gi, ''))) {\n needToFoldCase = true;\n ignoreCase = false;\n break;\n }\n }\n \n var escapeCharToCodeUnit = {\n 'b': 8,\n 't': 9,\n 'n': 0xa,\n 'v': 0xb,\n 'f': 0xc,\n 'r': 0xd\n };\n \n function decodeEscape(charsetPart) {\n var cc0 = charsetPart.charCodeAt(0);\n if (cc0 !== 92 /* \\\\ */) {\n return cc0;\n }\n var c1 = charsetPart.charAt(1);\n cc0 = escapeCharToCodeUnit[c1];\n if (cc0) {\n return cc0;\n } else if ('0' <= c1 && c1 <= '7') {\n return parseInt(charsetPart.substring(1), 8);\n } else if (c1 === 'u' || c1 === 'x') {\n return parseInt(charsetPart.substring(2), 16);\n } else {\n return charsetPart.charCodeAt(1);\n }\n }\n \n function encodeEscape(charCode) {\n if (charCode < 0x20) {\n return (charCode < 0x10 ? '\\\\x0' : '\\\\x') + charCode.toString(16);\n }\n var ch = String.fromCharCode(charCode);\n return (ch === '\\\\' || ch === '-' || ch === ']' || ch === '^')\n ? \"\\\\\" + ch : ch;\n }\n \n function caseFoldCharset(charSet) {\n var charsetParts = charSet.substring(1, charSet.length - 1).match(\n new RegExp(\n '\\\\\\\\u[0-9A-Fa-f]{4}'\n + '|\\\\\\\\x[0-9A-Fa-f]{2}'\n + '|\\\\\\\\[0-3][0-7]{0,2}'\n + '|\\\\\\\\[0-7]{1,2}'\n + '|\\\\\\\\[\\\\s\\\\S]'\n + '|-'\n + '|[^-\\\\\\\\]',\n 'g'));\n var ranges = [];\n var inverse = charsetParts[0] === '^';\n \n var out = ['['];\n if (inverse) { out.push('^'); }\n \n for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {\n var p = charsetParts[i];\n if (/\\\\[bdsw]/i.test(p)) { // Don't muck with named groups.\n out.push(p);\n } else {\n var start = decodeEscape(p);\n var end;\n if (i + 2 < n && '-' === charsetParts[i + 1]) {\n end = decodeEscape(charsetParts[i + 2]);\n i += 2;\n } else {\n end = start;\n }\n ranges.push([start, end]);\n // If the range might intersect letters, then expand it.\n // This case handling is too simplistic.\n // It does not deal with non-latin case folding.\n // It works for latin source code identifiers though.\n if (!(end < 65 || start > 122)) {\n if (!(end < 65 || start > 90)) {\n ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);\n }\n if (!(end < 97 || start > 122)) {\n ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);\n }\n }\n }\n }\n \n // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]\n // -> [[1, 12], [14, 14], [16, 17]]\n ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });\n var consolidatedRanges = [];\n var lastRange = [];\n for (var i = 0; i < ranges.length; ++i) {\n var range = ranges[i];\n if (range[0] <= lastRange[1] + 1) {\n lastRange[1] = Math.max(lastRange[1], range[1]);\n } else {\n consolidatedRanges.push(lastRange = range);\n }\n }\n \n for (var i = 0; i < consolidatedRanges.length; ++i) {\n var range = consolidatedRanges[i];\n out.push(encodeEscape(range[0]));\n if (range[1] > range[0]) {\n if (range[1] + 1 > range[0]) { out.push('-'); }\n out.push(encodeEscape(range[1]));\n }\n }\n out.push(']');\n return out.join('');\n }\n \n function allowAnywhereFoldCaseAndRenumberGroups(regex) {\n // Split into character sets, escape sequences, punctuation strings\n // like ('(', '(?:', ')', '^'), and runs of characters that do not\n // include any of the above.\n var parts = regex.source.match(\n new RegExp(\n '(?:'\n + '\\\\[(?:[^\\\\x5C\\\\x5D]|\\\\\\\\[\\\\s\\\\S])*\\\\]' // a character set\n + '|\\\\\\\\u[A-Fa-f0-9]{4}' // a unicode escape\n + '|\\\\\\\\x[A-Fa-f0-9]{2}' // a hex escape\n + '|\\\\\\\\[0-9]+' // a back-reference or octal escape\n + '|\\\\\\\\[^ux0-9]' // other escape sequence\n + '|\\\\(\\\\?[:!=]' // start of a non-capturing group\n + '|[\\\\(\\\\)\\\\^]' // start/end of a group, or line start\n + '|[^\\\\x5B\\\\x5C\\\\(\\\\)\\\\^]+' // run of other characters\n + ')',\n 'g'));\n var n = parts.length;\n \n // Maps captured group numbers to the number they will occupy in\n // the output or to -1 if that has not been determined, or to\n // undefined if they need not be capturing in the output.\n var capturedGroups = [];\n \n // Walk over and identify back references to build the capturedGroups\n // mapping.\n for (var i = 0, groupIndex = 0; i < n; ++i) {\n var p = parts[i];\n if (p === '(') {\n // groups are 1-indexed, so max group index is count of '('\n ++groupIndex;\n } else if ('\\\\' === p.charAt(0)) {\n var decimalValue = +p.substring(1);\n if (decimalValue) {\n if (decimalValue <= groupIndex) {\n capturedGroups[decimalValue] = -1;\n } else {\n // Replace with an unambiguous escape sequence so that\n // an octal escape sequence does not turn into a backreference\n // to a capturing group from an earlier regex.\n parts[i] = encodeEscape(decimalValue);\n }\n }\n }\n }\n \n // Renumber groups and reduce capturing groups to non-capturing groups\n // where possible.\n for (var i = 1; i < capturedGroups.length; ++i) {\n if (-1 === capturedGroups[i]) {\n capturedGroups[i] = ++capturedGroupIndex;\n }\n }\n for (var i = 0, groupIndex = 0; i < n; ++i) {\n var p = parts[i];\n if (p === '(') {\n ++groupIndex;\n if (!capturedGroups[groupIndex]) {\n parts[i] = '(?:';\n }\n } else if ('\\\\' === p.charAt(0)) {\n var decimalValue = +p.substring(1);\n if (decimalValue && decimalValue <= groupIndex) {\n parts[i] = '\\\\' + capturedGroups[decimalValue];\n }\n }\n }\n \n // Remove any prefix anchors so that the output will match anywhere.\n // ^^ really does mean an anchored match though.\n for (var i = 0; i < n; ++i) {\n if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }\n }\n \n // Expand letters to groups to handle mixing of case-sensitive and\n // case-insensitive patterns if necessary.\n if (regex.ignoreCase && needToFoldCase) {\n for (var i = 0; i < n; ++i) {\n var p = parts[i];\n var ch0 = p.charAt(0);\n if (p.length >= 2 && ch0 === '[') {\n parts[i] = caseFoldCharset(p);\n } else if (ch0 !== '\\\\') {\n // TODO: handle letters in numeric escapes.\n parts[i] = p.replace(\n /[a-zA-Z]/g,\n function (ch) {\n var cc = ch.charCodeAt(0);\n return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';\n });\n }\n }\n }\n \n return parts.join('');\n }\n \n var rewritten = [];\n for (var i = 0, n = regexs.length; i < n; ++i) {\n var regex = regexs[i];\n if (regex.global || regex.multiline) { throw new Error('' + regex); }\n rewritten.push(\n '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');\n }\n \n return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');\n }\n\n /**\n * Split markup into a string of source code and an array mapping ranges in\n * that string to the text nodes in which they appear.\n *\n * \n * The HTML DOM structure:
\n * \n * (Element \"p\"\n * (Element \"b\"\n * (Text \"print \")) ; #1\n * (Text \"'Hello '\") ; #2\n * (Element \"br\") ; #3\n * (Text \" + 'World';\")) ; #4\n *
\n * \n * corresponds to the HTML\n * {@code
print 'Hello '
+ 'World';
}.
\n *\n * \n * It will produce the output:
\n * \n * {\n * sourceCode: \"print 'Hello '\\n + 'World';\",\n * // 1 2\n * // 012345678901234 5678901234567\n * spans: [0, #1, 6, #2, 14, #3, 15, #4]\n * }\n * \n * \n * where #1 is a reference to the {@code \"print \"} text node above, and so\n * on for the other text nodes.\n *
\n *\n * \n * The {@code} spans array is an array of pairs. Even elements are the start\n * indices of substrings, and odd elements are the text nodes (or BR elements)\n * that contain the text for those substrings.\n * Substrings continue until the next index or the end of the source.\n *
\n *\n * @param {Node} node an HTML DOM subtree containing source-code.\n * @param {boolean} isPreformatted true if white-space in text nodes should\n * be considered significant.\n * @return {Object} source code and the text nodes in which they occur.\n */\n function extractSourceSpans(node, isPreformatted) {\n var nocode = /(?:^|\\s)nocode(?:\\s|$)/;\n \n var chunks = [];\n var length = 0;\n var spans = [];\n var k = 0;\n \n function walk(node) {\n var type = node.nodeType;\n if (type == 1) { // Element\n if (nocode.test(node.className)) { return; }\n for (var child = node.firstChild; child; child = child.nextSibling) {\n walk(child);\n }\n var nodeName = node.nodeName.toLowerCase();\n if ('br' === nodeName || 'li' === nodeName) {\n chunks[k] = '\\n';\n spans[k << 1] = length++;\n spans[(k++ << 1) | 1] = node;\n }\n } else if (type == 3 || type == 4) { // Text\n var text = node.nodeValue;\n if (text.length) {\n if (!isPreformatted) {\n text = text.replace(/[ \\t\\r\\n]+/g, ' ');\n } else {\n text = text.replace(/\\r\\n?/g, '\\n'); // Normalize newlines.\n }\n // TODO: handle tabs here?\n chunks[k] = text;\n spans[k << 1] = length;\n length += text.length;\n spans[(k++ << 1) | 1] = node;\n }\n }\n }\n \n walk(node);\n \n return {\n sourceCode: chunks.join('').replace(/\\n$/, ''),\n spans: spans\n };\n }\n\n /**\n * Apply the given language handler to sourceCode and add the resulting\n * decorations to out.\n * @param {number} basePos the index of sourceCode within the chunk of source\n * whose decorations are already present on out.\n */\n function appendDecorations(basePos, sourceCode, langHandler, out) {\n if (!sourceCode) { return; }\n var job = {\n sourceCode: sourceCode,\n basePos: basePos\n };\n langHandler(job);\n out.push.apply(out, job.decorations);\n }\n\n var notWs = /\\S/;\n\n /**\n * Given an element, if it contains only one child element and any text nodes\n * it contains contain only space characters, return the sole child element.\n * Otherwise returns undefined.\n * \n * This is meant to return the CODE element in {@code
} when\n * there is a single child element that contains all the non-space textual\n * content, but not to return anything where there are multiple child elements\n * as in {@code ......
} or when there\n * is textual content.\n */\n function childContentWrapper(element) {\n var wrapper = undefined;\n for (var c = element.firstChild; c; c = c.nextSibling) {\n var type = c.nodeType;\n wrapper = (type === 1) // Element Node\n ? (wrapper ? element : c)\n : (type === 3) // Text Node\n ? (notWs.test(c.nodeValue) ? element : wrapper)\n : wrapper;\n }\n return wrapper === element ? undefined : wrapper;\n }\n\n /** Given triples of [style, pattern, context] returns a lexing function,\n * The lexing function interprets the patterns to find token boundaries and\n * returns a decoration list of the form\n * [index_0, style_0, index_1, style_1, ..., index_n, style_n]\n * where index_n is an index into the sourceCode, and style_n is a style\n * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to\n * all characters in sourceCode[index_n-1:index_n].\n *\n * The stylePatterns is a list whose elements have the form\n * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].\n *\n * Style is a style constant like PR_PLAIN, or can be a string of the\n * form 'lang-FOO', where FOO is a language extension describing the\n * language of the portion of the token in $1 after pattern executes.\n * E.g., if style is 'lang-lisp', and group 1 contains the text\n * '(hello (world))', then that portion of the token will be passed to the\n * registered lisp handler for formatting.\n * The text before and after group 1 will be restyled using this decorator\n * so decorators should take care that this doesn't result in infinite\n * recursion. For example, the HTML lexer rule for SCRIPT elements looks\n * something like ['lang-js', /<[s]cript>(.+?)<\\/script>/]. This may match\n * '}\n * define style rules. See the example page for examples.\n * mark the {@code } and {@code } tags in your source with\n * {@code class=prettyprint.}\n * You can also use the (html deprecated) {@code } tag, but the pretty\n * printer needs to do more substantial DOM manipulations to support that, so\n * some css styles may not be preserved.\n * \n * That's it. I wanted to keep the API as simple as possible, so there's no\n * need to specify which language the code is in, but if you wish, you can add\n * another class to the {@code } or {@code } element to specify the\n * language, as in {@code }. Any class that\n * starts with \"lang-\" followed by a file extension, specifies the file type.\n * See the \"lang-*.js\" files in this directory for code that implements\n * per-language file handlers.\n * \n * Change log:
\n * cbeust, 2006/08/22\n *
\n * Java annotations (start with \"@\") are now captured as literals (\"lit\")\n *
\n * @requires console\n */\n\n// JSLint declarations\n/*global console, document, navigator, setTimeout, window, define */\n\n/** @define {boolean} */\nvar IN_GLOBAL_SCOPE = true;\n\n/**\n * Split {@code prettyPrint} into multiple timeouts so as not to interfere with\n * UI events.\n * If set to {@code false}, {@code prettyPrint()} is synchronous.\n */\nwindow['PR_SHOULD_USE_CONTINUATION'] = true;\n\n/**\n * Pretty print a chunk of code.\n * @param {string} sourceCodeHtml The HTML to pretty print.\n * @param {string} opt_langExtension The language name to use.\n * Typically, a filename extension like 'cpp' or 'java'.\n * @param {number|boolean} opt_numberLines True to number lines,\n * or the 1-indexed number of the first line in sourceCodeHtml.\n * @return {string} code as html, but prettier\n */\nvar prettyPrintOne;\n/**\n * Find all the {@code } and {@code } tags in the DOM with\n * {@code class=prettyprint} and prettify them.\n *\n * @param {Function} opt_whenDone called when prettifying is done.\n * @param {HTMLElement|HTMLDocument} opt_root an element or document\n * containing all the elements to pretty print.\n * Defaults to {@code document.body}.\n */\nvar prettyPrint;\n\n\n(function () {\n var win = window;\n // Keyword lists for various languages.\n // We use things that coerce to strings to make them compact when minified\n // and to defeat aggressive optimizers that fold large string constants.\n var FLOW_CONTROL_KEYWORDS = [\"break,continue,do,else,for,if,return,while\"];\n var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,\"auto,case,char,const,default,\" + \n \"double,enum,extern,float,goto,inline,int,long,register,short,signed,\" +\n \"sizeof,static,struct,switch,typedef,union,unsigned,void,volatile\"];\n var COMMON_KEYWORDS = [C_KEYWORDS,\"catch,class,delete,false,import,\" +\n \"new,operator,private,protected,public,this,throw,true,try,typeof\"];\n var CPP_KEYWORDS = [COMMON_KEYWORDS,\"alignof,align_union,asm,axiom,bool,\" +\n \"concept,concept_map,const_cast,constexpr,decltype,delegate,\" +\n \"dynamic_cast,explicit,export,friend,generic,late_check,\" +\n \"mutable,namespace,nullptr,property,reinterpret_cast,static_assert,\" +\n \"static_cast,template,typeid,typename,using,virtual,where\"];\n var JAVA_KEYWORDS = [COMMON_KEYWORDS,\n \"abstract,assert,boolean,byte,extends,final,finally,implements,import,\" +\n \"instanceof,interface,null,native,package,strictfp,super,synchronized,\" +\n \"throws,transient\"];\n var CSHARP_KEYWORDS = [JAVA_KEYWORDS,\n \"as,base,by,checked,decimal,delegate,descending,dynamic,event,\" +\n \"fixed,foreach,from,group,implicit,in,internal,into,is,let,\" +\n \"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,\" +\n \"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,\" +\n \"var,virtual,where\"];\n var COFFEE_KEYWORDS = \"all,and,by,catch,class,else,extends,false,finally,\" +\n \"for,if,in,is,isn't,loop,new,no,not,null,of,off,on,or,return,super,then,\" +\n \"throw,true,try,unless,until,when,while,yes\";\n var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,\n \"debugger,eval,export,function,get,null,set,undefined,var,with,\" +\n \"Infinity,NaN\"];\n var PERL_KEYWORDS = \"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,\" +\n \"goto,if,import,last,local,my,next,no,our,print,package,redo,require,\" +\n \"sub,undef,unless,until,use,wantarray,while,BEGIN,END\";\n var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"and,as,assert,class,def,del,\" +\n \"elif,except,exec,finally,from,global,import,in,is,lambda,\" +\n \"nonlocal,not,or,pass,print,raise,try,with,yield,\" +\n \"False,True,None\"];\n var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"alias,and,begin,case,class,\" +\n \"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,\" +\n \"rescue,retry,self,super,then,true,undef,unless,until,when,yield,\" +\n \"BEGIN,END\"];\n var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"as,assert,const,copy,drop,\" +\n \"enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,\" +\n \"pub,pure,ref,self,static,struct,true,trait,type,unsafe,use\"];\n var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, \"case,done,elif,esac,eval,fi,\" +\n \"function,in,local,set,then,until\"];\n var ALL_KEYWORDS = [\n CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,\n PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];\n var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\\d*)\\b/;\n\n // token style names. correspond to css classes\n /**\n * token style for a string literal\n * @const\n */\n var PR_STRING = 'str';\n /**\n * token style for a keyword\n * @const\n */\n var PR_KEYWORD = 'kwd';\n /**\n * token style for a comment\n * @const\n */\n var PR_COMMENT = 'com';\n /**\n * token style for a type\n * @const\n */\n var PR_TYPE = 'typ';\n /**\n * token style for a literal value. e.g. 1, null, true.\n * @const\n */\n var PR_LITERAL = 'lit';\n /**\n * token style for a punctuation string.\n * @const\n */\n var PR_PUNCTUATION = 'pun';\n /**\n * token style for plain text.\n * @const\n */\n var PR_PLAIN = 'pln';\n\n /**\n * token style for an sgml tag.\n * @const\n */\n var PR_TAG = 'tag';\n /**\n * token style for a markup declaration such as a DOCTYPE.\n * @const\n */\n var PR_DECLARATION = 'dec';\n /**\n * token style for embedded source.\n * @const\n */\n var PR_SOURCE = 'src';\n /**\n * token style for an sgml attribute name.\n * @const\n */\n var PR_ATTRIB_NAME = 'atn';\n /**\n * token style for an sgml attribute value.\n * @const\n */\n var PR_ATTRIB_VALUE = 'atv';\n\n /**\n * A class that indicates a section of markup that is not code, e.g. to allow\n * embedding of line numbers within code listings.\n * @const\n */\n var PR_NOCODE = 'nocode';\n\n \n \n /**\n * A set of tokens that can precede a regular expression literal in\n * javascript\n * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html\n * has the full list, but I've removed ones that might be problematic when\n * seen in languages that don't support regular expression literals.\n *\n * Specifically, I've removed any keywords that can't precede a regexp\n * literal in a syntactically legal javascript program, and I've removed the\n * \"in\" keyword since it's not a keyword in many languages, and might be used\n * as a count of inches.\n *\n *
The link above does not accurately describe EcmaScript rules since\n * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works\n * very well in practice.\n *\n * @private\n * @const\n */\n var REGEXP_PRECEDER_PATTERN = '(?:^^\\\\.?|[+-]|[!=]=?=?|\\\\#|%=?|&&?=?|\\\\(|\\\\*=?|[+\\\\-]=|->|\\\\/=?|::?|<=?|>>?>?=?|,|;|\\\\?|@|\\\\[|~|{|\\\\^\\\\^?=?|\\\\|\\\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\\\s*';\n \n // CAVEAT: this does not properly handle the case where a regular\n // expression immediately follows another since a regular expression may\n // have flags for case-sensitivity and the like. Having regexp tokens\n // adjacent is not valid in any language I'm aware of, so I'm punting.\n // TODO: maybe style special characters inside a regexp as punctuation.\n\n /**\n * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally\n * matches the union of the sets of strings matched by the input RegExp.\n * Since it matches globally, if the input strings have a start-of-input\n * anchor (/^.../), it is ignored for the purposes of unioning.\n * @param {Array.} regexs non multiline, non-global regexs.\n * @return {RegExp} a global regex.\n */\n function combinePrefixPatterns(regexs) {\n var capturedGroupIndex = 0;\n \n var needToFoldCase = false;\n var ignoreCase = false;\n for (var i = 0, n = regexs.length; i < n; ++i) {\n var regex = regexs[i];\n if (regex.ignoreCase) {\n ignoreCase = true;\n } else if (/[a-z]/i.test(regex.source.replace(\n /\\\\u[0-9a-f]{4}|\\\\x[0-9a-f]{2}|\\\\[^ux]/gi, ''))) {\n needToFoldCase = true;\n ignoreCase = false;\n break;\n }\n }\n \n var escapeCharToCodeUnit = {\n 'b': 8,\n 't': 9,\n 'n': 0xa,\n 'v': 0xb,\n 'f': 0xc,\n 'r': 0xd\n };\n \n function decodeEscape(charsetPart) {\n var cc0 = charsetPart.charCodeAt(0);\n if (cc0 !== 92 /* \\\\ */) {\n return cc0;\n }\n var c1 = charsetPart.charAt(1);\n cc0 = escapeCharToCodeUnit[c1];\n if (cc0) {\n return cc0;\n } else if ('0' <= c1 && c1 <= '7') {\n return parseInt(charsetPart.substring(1), 8);\n } else if (c1 === 'u' || c1 === 'x') {\n return parseInt(charsetPart.substring(2), 16);\n } else {\n return charsetPart.charCodeAt(1);\n }\n }\n \n function encodeEscape(charCode) {\n if (charCode < 0x20) {\n return (charCode < 0x10 ? '\\\\x0' : '\\\\x') + charCode.toString(16);\n }\n var ch = String.fromCharCode(charCode);\n return (ch === '\\\\' || ch === '-' || ch === ']' || ch === '^')\n ? \"\\\\\" + ch : ch;\n }\n \n function caseFoldCharset(charSet) {\n var charsetParts = charSet.substring(1, charSet.length - 1).match(\n new RegExp(\n '\\\\\\\\u[0-9A-Fa-f]{4}'\n + '|\\\\\\\\x[0-9A-Fa-f]{2}'\n + '|\\\\\\\\[0-3][0-7]{0,2}'\n + '|\\\\\\\\[0-7]{1,2}'\n + '|\\\\\\\\[\\\\s\\\\S]'\n + '|-'\n + '|[^-\\\\\\\\]',\n 'g'));\n var ranges = [];\n var inverse = charsetParts[0] === '^';\n \n var out = ['['];\n if (inverse) { out.push('^'); }\n \n for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {\n var p = charsetParts[i];\n if (/\\\\[bdsw]/i.test(p)) { // Don't muck with named groups.\n out.push(p);\n } else {\n var start = decodeEscape(p);\n var end;\n if (i + 2 < n && '-' === charsetParts[i + 1]) {\n end = decodeEscape(charsetParts[i + 2]);\n i += 2;\n } else {\n end = start;\n }\n ranges.push([start, end]);\n // If the range might intersect letters, then expand it.\n // This case handling is too simplistic.\n // It does not deal with non-latin case folding.\n // It works for latin source code identifiers though.\n if (!(end < 65 || start > 122)) {\n if (!(end < 65 || start > 90)) {\n ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);\n }\n if (!(end < 97 || start > 122)) {\n ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);\n }\n }\n }\n }\n \n // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]\n // -> [[1, 12], [14, 14], [16, 17]]\n ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });\n var consolidatedRanges = [];\n var lastRange = [];\n for (var i = 0; i < ranges.length; ++i) {\n var range = ranges[i];\n if (range[0] <= lastRange[1] + 1) {\n lastRange[1] = Math.max(lastRange[1], range[1]);\n } else {\n consolidatedRanges.push(lastRange = range);\n }\n }\n \n for (var i = 0; i < consolidatedRanges.length; ++i) {\n var range = consolidatedRanges[i];\n out.push(encodeEscape(range[0]));\n if (range[1] > range[0]) {\n if (range[1] + 1 > range[0]) { out.push('-'); }\n out.push(encodeEscape(range[1]));\n }\n }\n out.push(']');\n return out.join('');\n }\n \n function allowAnywhereFoldCaseAndRenumberGroups(regex) {\n // Split into character sets, escape sequences, punctuation strings\n // like ('(', '(?:', ')', '^'), and runs of characters that do not\n // include any of the above.\n var parts = regex.source.match(\n new RegExp(\n '(?:'\n + '\\\\[(?:[^\\\\x5C\\\\x5D]|\\\\\\\\[\\\\s\\\\S])*\\\\]' // a character set\n + '|\\\\\\\\u[A-Fa-f0-9]{4}' // a unicode escape\n + '|\\\\\\\\x[A-Fa-f0-9]{2}' // a hex escape\n + '|\\\\\\\\[0-9]+' // a back-reference or octal escape\n + '|\\\\\\\\[^ux0-9]' // other escape sequence\n + '|\\\\(\\\\?[:!=]' // start of a non-capturing group\n + '|[\\\\(\\\\)\\\\^]' // start/end of a group, or line start\n + '|[^\\\\x5B\\\\x5C\\\\(\\\\)\\\\^]+' // run of other characters\n + ')',\n 'g'));\n var n = parts.length;\n \n // Maps captured group numbers to the number they will occupy in\n // the output or to -1 if that has not been determined, or to\n // undefined if they need not be capturing in the output.\n var capturedGroups = [];\n \n // Walk over and identify back references to build the capturedGroups\n // mapping.\n for (var i = 0, groupIndex = 0; i < n; ++i) {\n var p = parts[i];\n if (p === '(') {\n // groups are 1-indexed, so max group index is count of '('\n ++groupIndex;\n } else if ('\\\\' === p.charAt(0)) {\n var decimalValue = +p.substring(1);\n if (decimalValue) {\n if (decimalValue <= groupIndex) {\n capturedGroups[decimalValue] = -1;\n } else {\n // Replace with an unambiguous escape sequence so that\n // an octal escape sequence does not turn into a backreference\n // to a capturing group from an earlier regex.\n parts[i] = encodeEscape(decimalValue);\n }\n }\n }\n }\n \n // Renumber groups and reduce capturing groups to non-capturing groups\n // where possible.\n for (var i = 1; i < capturedGroups.length; ++i) {\n if (-1 === capturedGroups[i]) {\n capturedGroups[i] = ++capturedGroupIndex;\n }\n }\n for (var i = 0, groupIndex = 0; i < n; ++i) {\n var p = parts[i];\n if (p === '(') {\n ++groupIndex;\n if (!capturedGroups[groupIndex]) {\n parts[i] = '(?:';\n }\n } else if ('\\\\' === p.charAt(0)) {\n var decimalValue = +p.substring(1);\n if (decimalValue && decimalValue <= groupIndex) {\n parts[i] = '\\\\' + capturedGroups[decimalValue];\n }\n }\n }\n \n // Remove any prefix anchors so that the output will match anywhere.\n // ^^ really does mean an anchored match though.\n for (var i = 0; i < n; ++i) {\n if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }\n }\n \n // Expand letters to groups to handle mixing of case-sensitive and\n // case-insensitive patterns if necessary.\n if (regex.ignoreCase && needToFoldCase) {\n for (var i = 0; i < n; ++i) {\n var p = parts[i];\n var ch0 = p.charAt(0);\n if (p.length >= 2 && ch0 === '[') {\n parts[i] = caseFoldCharset(p);\n } else if (ch0 !== '\\\\') {\n // TODO: handle letters in numeric escapes.\n parts[i] = p.replace(\n /[a-zA-Z]/g,\n function (ch) {\n var cc = ch.charCodeAt(0);\n return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';\n });\n }\n }\n }\n \n return parts.join('');\n }\n \n var rewritten = [];\n for (var i = 0, n = regexs.length; i < n; ++i) {\n var regex = regexs[i];\n if (regex.global || regex.multiline) { throw new Error('' + regex); }\n rewritten.push(\n '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');\n }\n \n return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');\n }\n\n /**\n * Split markup into a string of source code and an array mapping ranges in\n * that string to the text nodes in which they appear.\n *\n * \n * The HTML DOM structure:
\n * \n * (Element \"p\"\n * (Element \"b\"\n * (Text \"print \")) ; #1\n * (Text \"'Hello '\") ; #2\n * (Element \"br\") ; #3\n * (Text \" + 'World';\")) ; #4\n *
\n * \n * corresponds to the HTML\n * {@code
print 'Hello '
+ 'World';
}.
\n *\n * \n * It will produce the output:
\n * \n * {\n * sourceCode: \"print 'Hello '\\n + 'World';\",\n * // 1 2\n * // 012345678901234 5678901234567\n * spans: [0, #1, 6, #2, 14, #3, 15, #4]\n * }\n * \n * \n * where #1 is a reference to the {@code \"print \"} text node above, and so\n * on for the other text nodes.\n *
\n *\n * \n * The {@code} spans array is an array of pairs. Even elements are the start\n * indices of substrings, and odd elements are the text nodes (or BR elements)\n * that contain the text for those substrings.\n * Substrings continue until the next index or the end of the source.\n *
\n *\n * @param {Node} node an HTML DOM subtree containing source-code.\n * @param {boolean} isPreformatted true if white-space in text nodes should\n * be considered significant.\n * @return {Object} source code and the text nodes in which they occur.\n */\n function extractSourceSpans(node, isPreformatted) {\n var nocode = /(?:^|\\s)nocode(?:\\s|$)/;\n \n var chunks = [];\n var length = 0;\n var spans = [];\n var k = 0;\n \n function walk(node) {\n var type = node.nodeType;\n if (type == 1) { // Element\n if (nocode.test(node.className)) { return; }\n for (var child = node.firstChild; child; child = child.nextSibling) {\n walk(child);\n }\n var nodeName = node.nodeName.toLowerCase();\n if ('br' === nodeName || 'li' === nodeName) {\n chunks[k] = '\\n';\n spans[k << 1] = length++;\n spans[(k++ << 1) | 1] = node;\n }\n } else if (type == 3 || type == 4) { // Text\n var text = node.nodeValue;\n if (text.length) {\n if (!isPreformatted) {\n text = text.replace(/[ \\t\\r\\n]+/g, ' ');\n } else {\n text = text.replace(/\\r\\n?/g, '\\n'); // Normalize newlines.\n }\n // TODO: handle tabs here?\n chunks[k] = text;\n spans[k << 1] = length;\n length += text.length;\n spans[(k++ << 1) | 1] = node;\n }\n }\n }\n \n walk(node);\n \n return {\n sourceCode: chunks.join('').replace(/\\n$/, ''),\n spans: spans\n };\n }\n\n /**\n * Apply the given language handler to sourceCode and add the resulting\n * decorations to out.\n * @param {number} basePos the index of sourceCode within the chunk of source\n * whose decorations are already present on out.\n */\n function appendDecorations(basePos, sourceCode, langHandler, out) {\n if (!sourceCode) { return; }\n var job = {\n sourceCode: sourceCode,\n basePos: basePos\n };\n langHandler(job);\n out.push.apply(out, job.decorations);\n }\n\n var notWs = /\\S/;\n\n /**\n * Given an element, if it contains only one child element and any text nodes\n * it contains contain only space characters, return the sole child element.\n * Otherwise returns undefined.\n * \n * This is meant to return the CODE element in {@code
} when\n * there is a single child element that contains all the non-space textual\n * content, but not to return anything where there are multiple child elements\n * as in {@code ......
} or when there\n * is textual content.\n */\n function childContentWrapper(element) {\n var wrapper = undefined;\n for (var c = element.firstChild; c; c = c.nextSibling) {\n var type = c.nodeType;\n wrapper = (type === 1) // Element Node\n ? (wrapper ? element : c)\n : (type === 3) // Text Node\n ? (notWs.test(c.nodeValue) ? element : wrapper)\n : wrapper;\n }\n return wrapper === element ? undefined : wrapper;\n }\n\n /** Given triples of [style, pattern, context] returns a lexing function,\n * The lexing function interprets the patterns to find token boundaries and\n * returns a decoration list of the form\n * [index_0, style_0, index_1, style_1, ..., index_n, style_n]\n * where index_n is an index into the sourceCode, and style_n is a style\n * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to\n * all characters in sourceCode[index_n-1:index_n].\n *\n * The stylePatterns is a list whose elements have the form\n * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].\n *\n * Style is a style constant like PR_PLAIN, or can be a string of the\n * form 'lang-FOO', where FOO is a language extension describing the\n * language of the portion of the token in $1 after pattern executes.\n * E.g., if style is 'lang-lisp', and group 1 contains the text\n * '(hello (world))', then that portion of the token will be passed to the\n * registered lisp handler for formatting.\n * The text before and after group 1 will be restyled using this decorator\n * so decorators should take care that this doesn't result in infinite\n * recursion. For example, the HTML lexer rule for SCRIPT elements looks\n * something like ['lang-js', /<[s]cript>(.+?)<\\/script>/]. This may match\n * '